Sub topic 6
Running CPU-bound work in parallel with threads
This chapter assumes you know the threading module or concurrent.futures, the difference between threads and processes, and the basic idea of a race condition. It builds on the earlier chapters about how the GIL serializes bytecode and how to detect a free-threaded build.
The idea
A CPU-bound task spends its time computing, not waiting on I/O. With the GIL, only one thread executes Python bytecode at a time, so four threads on four cores run no faster than one. On a free-threaded build (for example python3.13t), threads can run bytecode at the same moment on different cores.
You do not need new APIs. The same threading and concurrent.futures code can run in parallel once the GIL is off.
A CPU-bound example
The function below counts primes with plain Python loops. Nothing in it releases the GIL or calls C code that does, so it is a fair test of bytecode parallelism.
from concurrent.futures import 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))
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(count_primes, [200_000] * 4))
print(results)Each of the four tasks is independent and shares no mutable state, so it needs no locks. Each call returns the same count, so results is a list of four equal numbers.
Comparing the two builds
Time the script on both interpreters. Check first that the GIL is really off, because a free-threaded build can re-enable it (for example when it loads an incompatible extension).
import sys
print("GIL enabled:", sys._is_gil_enabled())time python3.13 script.py # standard build, GIL on
time python3.13t script.py # free-threaded build, GIL offExpect the standard build to take about four times as long as a single task, since the threads take turns. On the free-threaded build with at least four idle cores, wall-clock time should be close to that of one task. Exact numbers depend on your machine.
What to watch for
- Core count limits the gain. Four threads on two cores give about a 2x speedup at best. Set
max_workersnearos.cpu_count()for CPU-bound work. - Single-thread speed. The free-threaded build can run single-threaded code somewhat slower than the standard build. Measure with your own workload before switching.
- Shared state is now unsafe. Tasks that update shared variables can interleave in ways the GIL used to hide. The next chapters cover this.
- Silent GIL re-enabling. If a C extension does not declare free-threaded support, the interpreter turns the GIL back on and your speedup disappears. Always print
sys._is_gil_enabled()when benchmarking. - Small tasks. Splitting work into very small pieces adds scheduling overhead. Give each thread enough work to take a meaningful fraction of a second.
Threads or processes?
Processes also give CPU parallelism on any build, but they copy or serialize data between workers and use more memory. Threads share memory directly, which makes passing large data cheap. The price is that you must make shared access safe yourself.
Exercise
You run the prime-counting script with four threads on a free-threaded build, but it takes as long as four sequential runs. Name two checks you should make.
Show answer
First, print sys._is_gil_enabled(). If it returns True, the GIL is on, either because of PYTHON_GIL=1 or because an imported extension forced it back on. Second, check the number of available cores with os.cpu_count(), and make sure other processes are not using them. If only one core is free, threads cannot run in parallel.