Sub topic 13
Performance trade-offs and choosing between threads and processes
This chapter assumes you know the threading module and concurrent.futures. It also assumes you know the basic difference between threads and processes, and why shared mutable state needs locks. You have seen how a free-threaded build lets threads run Python code on several cores. Now you decide when that helps and when another tool fits better.
What free-threading costs
Removing the GIL is not free. A free-threaded build changes how the interpreter manages memory and object access, so it carries overhead that a standard build does not.
- Single-thread slowdown. Code that runs on one thread can be slower than on a standard build. The size depends on the build, the version and the workload. Measure your own code instead of trusting a general figure.
- Memory use. Objects carry extra bookkeeping for thread-safe reference counting, and the allocator is different. Programs with many small objects may use more memory.
- Lock contention. Threads that fight over the same lock or the same object wait for each other. Adding threads then gives no speedup, or makes things slower.
- Compatibility. A C extension that has not declared free-threading support makes the interpreter turn the GIL back on, as the earlier chapter on extensions explained. You then lose the parallelism.
What threads and processes each give you
| Property | Threads (free-threaded) | Processes (`multiprocessing`) |
|---|---|---|
| Memory | Shared, no copying | Separate, data is copied or pickled |
| Startup cost | Low | Higher |
| Communication | Direct access to shared objects | Pipes, queues, shared memory |
| Isolation | None, a bug can corrupt shared state | Strong, a crash stays in one process |
| Main risk | Data races | Serialization cost and memory duplication |
Threads win when workers need to read the same large data. A process pool would pickle that data and send it to each worker, or hold one copy per process. Processes win when you want isolation, or when you must run on a standard build.
A simple benchmark
Time the same CPU-bound job with both pools. This script uses the prime counter from earlier in the tutorial.
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
def timed(executor_cls, workers):
start = time.perf_counter()
with executor_cls(max_workers=workers) as pool:
list(pool.map(count_primes, [200_000] * 4))
return time.perf_counter() - start
if __name__ == "__main__":
print(f"threads: {timed(ThreadPoolExecutor, 4):.2f}s")
print(f"processes: {timed(ProcessPoolExecutor, 4):.2f}s")On a standard build, the thread version runs about as slowly as doing the work in sequence, and the process version scales with your cores. On a free-threaded build, both can scale. The thread version avoids process startup and pickling, so it often has an edge on short tasks. Your numbers will vary with core count and Python version.
Choosing in practice
- I/O-bound work (network calls, disk, databases) already works well with threads or
asynciounder the GIL, because threads release it while they wait. Free-threading adds little here. - CPU-bound work on a free-threaded build is where threads now pay off, especially with shared data.
- CPU-bound work on a standard build still needs processes.
- Many short tasks favor threads, since process startup and pickling dominate small jobs.
- Untrusted or crash-prone code favors processes for isolation.
Check the scaling yourself. Run the workload with 1, 2, 4 and 8 workers and record the time. If the time stops dropping, look for lock contention, memory bandwidth limits, or a single serial step in the program.
Exercise
Your service does CPU-bound image processing. Workers all read one 2 GB lookup table and never modify it. You can run either a free-threaded build with compatible dependencies or a standard build. Which setup do you pick, and why?
Show answer
Use threads on the free-threaded build. The workers can share the one 2 GB table in memory. A process pool would either hold one copy per process or pay the cost of sending the data between processes. Because the table is read-only, no locks are needed for it. Confirm with a benchmark, and check that no dependency re-enables the GIL.
Exercise
Name two reasons a free-threaded program might show no speedup when you add threads.
Show answer
Any two of these: threads contend for a shared lock, so they run one at a time. A C extension re-enabled the GIL. The machine has fewer free cores than threads. A serial step in the program dominates the run time.