Sub topic 2
How the GIL limits CPU-bound threads
This chapter assumes you can write basic Python functions, have used threading or concurrent.futures, and know the difference between a thread and a process. It builds on the previous chapter's description of the Global Interpreter Lock (GIL), the mutex that lets only one thread execute Python bytecode at a time in standard CPython.
CPU-bound versus I/O-bound work
A task is I/O-bound when it spends most of its time waiting, for example on a network response or a disk read. A task is CPU-bound when it spends most of its time computing, for example checking numbers for primality.
The GIL affects these two kinds of work differently:
- I/O-bound threads release the GIL while they wait. Another thread can run Python code in the meantime, so threads overlap well.
- CPU-bound threads hold the GIL while they run bytecode. Only one of them makes progress at any moment, no matter how many cores the machine has.
How threads take turns
A thread must hold the GIL to run bytecode. The interpreter asks a running thread to give up the GIL after a fixed interval, 5 milliseconds by default. A waiting thread then takes it. The check happens between bytecode instructions, so a thread can also hand over the GIL earlier, for example when it starts blocking I/O.
The threads are real operating system threads, and the OS could schedule them on different cores. The GIL stops them from running Python code at the same time. Switching also has a cost, so CPU-bound threads under the GIL can be slightly slower than running the same work in one thread.
Measuring the effect
The next program counts primes in a pure-Python loop. It runs the same work first in one thread, then spread across four threads.
import time
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__":
start = time.perf_counter()
for _ in range(4):
count_primes(200_000)
print(f"Sequential: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(count_primes, [200_000] * 4))
print(f"Four threads: {time.perf_counter() - start:.2f}s")On a standard build, the two times come out about equal, and the threaded run is often a little slower. Absolute numbers depend on your machine. On a four-core machine you might hope for a speedup near 4x, and the GIL prevents it.
Where threads still help
The GIL does not make threads useless. Threads still pay off in these cases:
- Waiting on sockets, files, or subprocesses, since blocking calls release the GIL.
- Calling C libraries that release the GIL during long computations. Parts of NumPy and
hashlibdo this. - Keeping a program responsive, for example running a background task while a user interface stays active.
Common workarounds and their costs
Before free-threading, the usual way to use several cores was multiprocessing or ProcessPoolExecutor. Each worker is a separate process with its own interpreter and its own GIL. This gives real parallelism, with these costs:
- Arguments and results are pickled and copied between processes.
- Each process uses its own memory, and startup is slower than for a thread.
- Sharing mutable state is harder than with threads.
Free-threaded Python aims to give CPU-bound threads real parallelism without these costs. The next chapters cover how it does that.
Exercise
A program downloads 50 web pages using 10 threads, then parses each page with a pure-Python function using 10 more threads. On a standard CPython build, which stage gains from threads, and why does the other not?
Show answer
The download stage gains, because threads waiting on network I/O release the GIL and let other threads run. The parsing stage does not gain, because it is CPU-bound pure-Python code. Each thread needs the GIL to run bytecode, so only one parses at a time. Processes, or a free-threaded build, are needed for parallel parsing.