Skip to main content

Programming languages · Advanced · 22 min

Speed up Python with threads, processes and concurrent.futures

By Padding · Updated 18 Nov 2026
Python 3.15.2 · uv 0.13 · python:3.15-slim

You will time a slow file job and a CPU-heavy hashing job, speed each one up with the right concurrent.futures pool, handle a failing worker, and measure what the free-threaded Python 3.15 build changes.

On this page

Python gives you two ready-made ways to run work side by side: a pool of threads and a pool of processes. Both live in concurrent.futures and share one interface, so switching between them is a one-word change. Picking the wrong one takes no more effort, and then the "faster" version runs at the same speed as the original, or slower.

The reason is the global interpreter lock (GIL). In the standard CPython build only one thread runs Python bytecode at any moment. A thread that is waiting, on a disk, a network or a sleep, lets go of the lock, so other threads can run while it waits. A thread that is calculating holds on to it. Processes sidestep the lock completely: each one is a separate interpreter with its own GIL, at the cost of start-up time and of copying arguments and results between processes.

You will see this for yourself with two jobs. One counts the words in 40 report files and spends nearly all its time waiting. The other hashes customer IDs thousands of times and spends all its time calculating. You time each one sequentially, on threads and on processes, then handle a worker that fails, trigger the classic __main__ mistake on purpose, and finish by running the hashing job on Python's free-threaded build, where the GIL is switched off.

Step 1 · Create the project and the sample files

Make a throwaway project folder. Everything in this tutorial uses the standard library, so there is nothing to add:

Bash
mkdir -p ~/pool-demo
cd ~/pool-demo
uv init --no-package

Write a script that creates 40 small text files in data/, each with 6,000 words:

Bash
cat > make_data.py <<'PY'
from pathlib import Path

WORDS = "market price stock order delivery invoice customer branch".split()

data = Path("data")
data.mkdir(exist_ok=True)
for n in range(1, 41):
    lines = [" ".join(WORDS[(n + i) % len(WORDS)] for i in range(12)) for _ in range(500)]
    (data / f"report-{n:02}.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
print("wrote", len(list(data.glob("*.txt"))), "files")
PY
uv run make_data.py

Check it worked

The script prints wrote 40 files. Now ask Python how many CPU cores it may use, because that number caps what processes can do for you later:

Bash
uv run python -c "import os; print(os.process_cpu_count())"

It prints a whole number, such as 4 or 8. os.process_cpu_count() counts the cores this process is allowed to run on, which can be fewer than the machine has. On a two-core laptop, a common budget machine in many places, the best a process pool can do for a CPU job is about twice as fast, so keep that ceiling in mind when you read your timings.

Step 2 · Write both jobs and time them one by one

Put the two jobs in a module, jobs.py, so every later script can import them:

Bash
cat > jobs.py <<'PY'
import hashlib
import time
from pathlib import Path

FILES = sorted(Path("data").glob("report-*.txt"))
SEEDS = [f"customer-{n}" for n in range(1, 9)]

# Each read waits 0.1 s first, the way a network share, a cloud bucket
# or a busy disk makes you wait. Remove the sleep and reads are near-instant.
LATENCY = 0.1


def count_words(path):
    time.sleep(LATENCY)
    return len(Path(path).read_text(encoding="utf-8").split())


def hash_seed(seed, rounds=300_000):
    if not seed:
        raise ValueError("seed must not be empty")
    digest = seed.encode()
    for _ in range(rounds):
        digest = hashlib.blake2b(digest, digest_size=32).digest()
    return digest.hex()[:12]


def timed(label, fn):
    started = time.perf_counter()
    result = fn()
    print(f"{label:<12} {time.perf_counter() - started:6.2f} s")
    return result
PY

count_words is the I/O job. Files on your own SSD come back from the operating system's cache in microseconds, which would make the waiting invisible, so LATENCY adds the 0.1 seconds a slow store would cost. Delete that line later and point the function at a real network drive if you have one.

hash_seed is the CPU job. It feeds a hash back into itself 300,000 times, which is how key-stretching works when you store passwords. Each call to blake2b gets only 32 bytes. That detail matters: hashlib releases the GIL only when one call is given more than 2047 bytes, so this loop holds the lock the whole time, like most Python code that calculates.

timed runs a function, prints how long it took and returns its result. Now the baseline:

Bash
cat > baseline.py <<'PY'
from jobs import FILES, SEEDS, count_words, hash_seed, timed

words = timed("files", lambda: sum(count_words(p) for p in FILES))
digests = timed("hashing", lambda: [hash_seed(s) for s in SEEDS])
print(f"{len(FILES)} files, {words} words; {len(digests)} digests, first {digests[0]}")
PY
Bash
uv run baseline.py

Check it worked

The output is something like this, with your own hashing time:

Text
files          4.21 s
hashing        1.62 s
40 files, 240000 words; 8 digests, first 1c2e0a9f6d3b

The files line is just over 4 seconds, because 40 waits of 0.1 seconds run back to back. The last line reports 240,000 words and eight digests. Write both times down: they are the numbers to beat.

Step 3 · Run the file job on a thread pool

ThreadPoolExecutor.map works like the built-in map, except that it hands the calls to a pool of worker threads and gives back the results in the original order. Try the file job with 1, 5 and 20 threads:

Bash
cat > io_threads.py <<'PY'
from concurrent.futures import ThreadPoolExecutor

from jobs import FILES, count_words, timed


def read_all(workers):
    with ThreadPoolExecutor(max_workers=workers) as pool:
        return sum(pool.map(count_words, FILES))


for workers in (1, 5, 20):
    words = timed(f"{workers} threads", lambda: read_all(workers))
print(f"{words} words")
PY
Bash
uv run io_threads.py

While a thread sleeps or reads, it releases the GIL, so the other threads get on with their own files. The with block waits for every call to finish and then shuts the pool down. If you leave out max_workers, Python picks min(32, os.process_cpu_count() + 4) threads, a default meant for jobs like this one.

Check it worked

The output is something like:

Text
1 threads      4.21 s
5 threads      0.84 s
20 threads     0.23 s
240000 words

One thread matches the baseline. Five threads cut the time about five-fold, and 20 threads bring it down to a fraction of a second, with the same 240,000 words. Threads help this job even on a single-core machine, because the time saved is waiting time, not calculation.

Step 4 · Run the hashing job on threads, then on processes

This time use submit and as_completed instead of map. submit schedules one call and returns a Future, a placeholder for its result. as_completed hands back futures in the order they finish, which lets you deal with each result as soon as it is ready. A dictionary from future to seed remembers which result belongs to which input.

The same function runs the job on either kind of pool, because both classes have the same interface:

Bash
cat > cpu_pools.py <<'PY'
import os
import sys
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed

from jobs import SEEDS, hash_seed, timed

WORKERS = min(len(SEEDS), os.process_cpu_count() or 1)


def run_pool(pool_class):
    digests = {}
    with pool_class(max_workers=WORKERS) as pool:
        futures = {pool.submit(hash_seed, seed): seed for seed in SEEDS}
        for future in as_completed(futures):
            digests[futures[future]] = future.result()
    return digests


if __name__ == "__main__":
    gil = "on" if getattr(sys, "_is_gil_enabled", lambda: True)() else "off"
    print(f"Python {sys.version.split()[0]}, GIL {gil}, {WORKERS} workers")
    one = timed("one by one", lambda: {seed: hash_seed(seed) for seed in SEEDS})
    threads = timed("threads", lambda: run_pool(ThreadPoolExecutor))
    processes = timed("processes", lambda: run_pool(ProcessPoolExecutor))
    print("same digests:", one == threads == processes)
PY
Bash
uv run cpu_pools.py

sys._is_gil_enabled() reports whether the lock is active, which you will need in the last step. The pool size matches the cores you may use: more processes than cores only adds switching.

A process pool has to send each argument to a worker and each result back. It does that by pickling them, so only functions defined at the top level of a module, and arguments that can be pickled, work. A lambda passed to submit on a process pool fails. Here only short strings travel, so the copying cost is tiny; with large lists or data frames it can eat the gain.

Check it worked

On an eight-core machine the output is something like:

Text
Python 3.15.2, GIL on, 8 workers
one by one     1.62 s
threads        1.60 s
processes      0.55 s
same digests: True

Threads take about as long as one by one: eight threads, but only the one holding the GIL calculates. Processes are faster, roughly by the number of cores, minus a fraction of a second for starting the workers. same digests: True confirms that all three runs computed the same answers. On a two-core machine, expect processes to take a little over half the sequential time.

Step 5 · Handle an exception from a worker

A worker that raises does not crash your program. The pool catches the exception and stores it in the future. It comes back to you when you ask for the result: future.result() raises it again, and map raises it when your loop reaches the value that failed. hash_seed rejects an empty seed, so slip one into the list:

Bash
cat > errors.py <<'PY'
from concurrent.futures import ProcessPoolExecutor, as_completed

from jobs import hash_seed

SEEDS = ["customer-1", "", "customer-3", "customer-4"]

if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=2) as pool:
        futures = {pool.submit(hash_seed, seed, 50_000): seed for seed in SEEDS}
        for future in as_completed(futures):
            seed = futures[future]
            try:
                print(f"{seed!r}: {future.result()}")
            except ValueError as err:
                print(f"{seed!r} failed: {err}")

        print("with map:")
        results = pool.map(hash_seed, SEEDS, [50_000] * len(SEEDS))
        try:
            for seed, digest in zip(SEEDS, results):
                print(f"{seed!r}: {digest}")
        except ValueError as err:
            print(f"map stopped: {err}")
PY
uv run errors.py | tee errors.out

The extra argument, 50_000, asks for fewer rounds so the step runs quickly. map takes one iterable per function argument, which is why it gets a list of round counts next to the seeds.

Check it worked

The first block shows three digests and the line '' failed: seed must not be empty, in whichever order the workers finished. The other three seeds still get their results: one failure does not cancel the rest. After with map: you see the digest for 'customer-1' and then map stopped: seed must not be empty. The values after the failure are lost to that loop, even though the workers computed them. When every input matters, use submit with a try around each result(); use map when one failure should stop the batch.

Step 6 · See why processes need the __main__ guard

Every script in this tutorial that starts a process pool puts that code under if __name__ == "__main__":. Here is what happens without it:

Bash
cat > unguarded.py <<'PY'
import multiprocessing
from concurrent.futures import ProcessPoolExecutor

from jobs import SEEDS, hash_seed

print("starting the pool")
spawn = multiprocessing.get_context("spawn")
with ProcessPoolExecutor(max_workers=2, mp_context=spawn) as pool:
    print(list(pool.map(hash_seed, SEEDS)))
PY

Run it. It fails, and prints long tracebacks:

Bash
uv run unguarded.py

A new worker does not get a copy of your running program. It starts a fresh interpreter and imports your script, under the name __mp_main__, to find hash_seed and anything else it needs. Without the guard, that import runs the top-level code again, so each worker tries to start its own pool. Python refuses with a RuntimeError, the worker dies, and your pool reports BrokenProcessPool.

The script asks for the spawn start method so the failure looks the same everywhere. spawn is already the default on Windows and macOS. On Linux, the default since Python 3.14 is forkserver, and the multiprocessing documentation says the same unguarded code fails with it too. Only the older fork method lets it slip through, which is why scripts written on Linux years ago break when they reach a Mac.

Add the guard and the same code works:

Bash
cat > guarded.py <<'PY'
import multiprocessing
from concurrent.futures import ProcessPoolExecutor

from jobs import SEEDS, hash_seed

if __name__ == "__main__":
    print("starting the pool")
    spawn = multiprocessing.get_context("spawn")
    with ProcessPoolExecutor(max_workers=2, mp_context=spawn) as pool:
        print(list(pool.map(hash_seed, SEEDS)))
PY
uv run guarded.py | tee guarded.out

Check it worked

unguarded.py prints starting the pool more than once, once for your script and again for each worker that imported it, followed by a RuntimeError that mentions the bootstrapping phase and a final BrokenProcessPool line. guarded.py prints starting the pool once and then a list of eight 12-character digests. The same rule explains why process pools do not work from the interactive Python prompt: there is no file for the workers to import.

Step 7 · Try the free-threaded build

Since Python 3.13, CPython also comes as a free-threaded build, with the GIL switched off. It is an optional, separately installed interpreter, not the default, and its name ends in t. Install the 3.15 one with uv:

Bash
uv python install 3.15t

Run the same cpu_pools.py on it. --no-project tells uv to ignore the project's Python setting and use the interpreter you name:

Bash
uv run --no-project --python 3.15t cpu_pools.py

Check it worked

The first line now says GIL off, and the output is something like:

Text
Python 3.15.2, GIL off, 8 workers
one by one     1.35 s
threads        0.48 s
processes      0.53 s
same digests: True

The threads line has dropped to about the processes line: with no GIL, all eight threads calculate at once, and they skip the process start-up and pickling. Compare one by one with the same line from the standard build. The free-threaded build runs single-threaded Python code a little slower; the Python documentation measures the average cost at about 1% on macOS on Apple silicon and 8% on x86-64 Linux.

Before you move a real program onto it, check three things. Extension modules that are not marked as free-thread safe switch the GIL back on when you import them, with a warning, so test your full dependency list. Code written in C may hold its own locks and still run one thread at a time, so measure rather than assume. And your own code loses the accidental safety the GIL gave it: shared lists and counters that several threads update need a threading.Lock.

Step 8 · Clean up

Remove the demo project and the free-threaded interpreter. Python 3.15 and uv stay installed:

Bash
cd ~
rm -rf ~/pool-demo
uv python uninstall 3.15t

Check it worked

ls ~/pool-demo reports that there is no such file or directory, and uv python list --only-installed no longer shows a freethreaded entry for 3.15.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.