Sub topic 2
How the GIL limits CPU-bound threads
This chapter assumes you can write functions in Python and have used threading.Thread or concurrent.futures.ThreadPoolExecutor. It also assumes you know a thread is a unit of execution inside a process, and that you have a rough idea of what a race condition is. The previous chapter covered what the Global Interpreter Lock (GIL) is. This chapter covers what it does to your programs when threads need the CPU.
The core limit in one sentence
In a standard CPython build, only one thread at a time can execute Python bytecode. Threads still exist and the operating system still schedules them on different cores. But a thread must hold the GIL to run Python code, and there is one GIL per interpreter.
The consequence depends on what your threads spend their time doing:
- A CPU-bound thread spends its time computing: parsing, number crunching, hashing in pure Python. It needs the GIL almost continuously.
- An I/O-bound thread spends its time waiting: for a socket, a file, a database, or
time.sleep. It releases the GIL while it waits.
Threads help I/O-bound work because waiting threads give up the GIL. They do not help CPU-bound work, because no thread ever waits and the threads queue up for the single lock.
How threads take turns
A thread that wants to run asks for the GIL. If another thread holds it, the requester waits. The holder gives up the GIL in two situations:
- It makes a blocking call that releases the GIL, such as reading from a socket,
time.sleep(), orlock.acquire()when it has to wait. - It has held the GIL for longer than the switch interval and another thread is waiting. The waiting thread sets a flag, and the running thread drops the GIL at the next safe point in the interpreter loop.
You can read the interval from Python. The default is 5 milliseconds.
import sys
print(sys.getswitchinterval()) # 0.005 by defaultEach handoff costs time, because the interpreter must signal the other thread, and the operating system must wake it and often move it to another core. Two CPU-bound threads therefore do the same total work as one, plus the overhead of switching.
Measuring it
The following script runs the same CPU-bound function four times in sequence, then on four threads. Run it on a standard (not free-threaded) build.
import time
from concurrent.futures import ThreadPoolExecutor
def count_down(n):
while n > 0:
n -= 1
N = 20_000_000
TASKS = 4
def run_sequential():
for _ in range(TASKS):
count_down(N)
def run_threaded():
with ThreadPoolExecutor(max_workers=TASKS) as pool:
list(pool.map(count_down, [N] * TASKS))
def timed(label, fn):
start = time.perf_counter()
fn()
print(f"{label}: {time.perf_counter() - start:.2f} s")
if __name__ == "__main__":
timed("sequential", run_sequential)
timed("4 threads ", run_threaded)On a standard build, expect both timings to be roughly equal, and the threaded one is often slightly slower. The exact numbers depend on your machine, so compare the two figures to each other, not to any published value. A four-core machine does not give a 4x speedup, because the four threads take turns on one lock.
Now compare an I/O-style workload. Here time.sleep stands in for a network call.
import time
from concurrent.futures import ThreadPoolExecutor
def fake_request(_):
time.sleep(1)
if __name__ == "__main__":
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(fake_request, range(4)))
print(f"4 sleeping threads: {time.perf_counter() - start:.2f} s") # about 1 sFour one-second sleeps finish in about one second, because each sleeping thread releases the GIL. The difference between the two experiments is the whole story: threads overlap waiting, not computing.
Why threading can be slower than sequential code
Threaded CPU-bound code can lose to the sequential version. Three effects contribute:
- Switching overhead. Every GIL handoff involves locks, condition variables, and a context switch in the operating system.
- Cache disruption. When the GIL moves a thread to a different core, that thread's data may no longer be in the new core's cache.
- The convoy effect. When a CPU-bound thread runs alongside an I/O-bound thread, the I/O thread repeatedly finishes a wait, requests the GIL, and has to wait up to one switch interval before it can use it. Each short I/O operation then takes far longer than it should. A single heavy computation in a background thread can make a responsive thread feel sluggish.
Lowering the switch interval can reduce the latency for the I/O thread, but it raises the switching overhead. It changes who waits, not how much total computing gets done.
import sys
sys.setswitchinterval(0.001) # switch more often: lower latency, more overheadWhen the GIL is released for you
The GIL is a rule about Python bytecode. Code that runs outside the interpreter loop can release it. Common cases:
| Situation | Releases the GIL? | Threads help? |
|---|---|---|
| Pure-Python loops and arithmetic | No (only at switch points) | No |
| Socket, file, and subprocess I/O | Yes, while waiting | Yes |
| `time.sleep`, waiting on a lock or queue | Yes | Yes |
| `hashlib` on large buffers, `zlib` compression | Yes, for large inputs | Often |
| NumPy operations on large arrays | Often, inside the C loops | Often |
| A C extension that does not release it | No | No |
The last rows are why threads sometimes scale on numeric code even in a standard build: the heavy work happens in C, and the extension author chose to drop the GIL around it. This is a per-library decision, not something you can assume. Check the library's documentation, or measure.
What the GIL does and does not protect
The GIL keeps the interpreter's own state consistent, such as reference counts and the internal structure of built-in dicts and lists. That is its purpose, covered in the previous chapter. It does not make your code correct. A thread can lose the GIL between any two bytecode instructions, so a statement like counter += 1, which reads, adds, and writes back, can still interleave with another thread and lose an update.
The GIL narrows the window in which such races occur, which is why many programs run for years with latent races. This matters later in the tutorial: removing the GIL does not create these bugs, but it makes them far easier to trigger.
The usual workarounds and their costs
Because threads cannot run Python code in parallel, programs that need CPU parallelism have used other approaches:
multiprocessingorProcessPoolExecutor. Each worker is a separate process with its own interpreter and its own GIL. This gives real parallelism. The costs are higher memory use, process start-up time, and the need to serialize (pickle) arguments and results to move them between processes. Sharing large mutable state is awkward.- Native extensions that release the GIL. NumPy, or code written in Cython, C, C++ or Rust. This is fast but needs the work to be expressible in that library or language.
asyncio. This is a single thread that switches tasks atawaitpoints. It handles many concurrent I/O waits cheaply but does nothing for CPU-bound work.
Each of these works around the limit instead of removing it. The next chapters cover the proposal that removes the limit itself.
Diagnosing a GIL bottleneck
Use these checks when threaded code does not speed up:
- Watch CPU usage while the program runs. If the process stays near 100% of one core (for example, about 100% in
top) while using several threads, the threads are probably serialized by the GIL. - Compare wall-clock time for one worker and for N workers on the same total work. No improvement points at the GIL, or at a shared lock in your own code.
- Profile to confirm that the time is spent in pure-Python code and not in a C call that waits.
- Try the same workload with
ProcessPoolExecutor. If it scales and threads do not, the GIL is the likely cause.
Summary of the model
- One GIL per interpreter means one thread executes Python bytecode at a time.
- A thread gives up the GIL when it blocks on I/O or sleeps, or after the 5 ms switch interval when others are waiting.
- CPU-bound threads therefore take turns instead of running in parallel, and pay switching overhead on top.
- I/O-bound threads overlap well, but a CPU-bound thread can delay them (the convoy effect).
- Extensions that release the GIL are the exception, and it is a per-library property.
- The GIL does not make compound operations atomic.
Exercise
You run a CPU-bound pure-Python function on 8 threads on an 8-core machine using a standard CPython build. The total run time is about the same as running it sequentially, and top shows the process using about 100% CPU. Explain why. Then name two ways to get real parallelism for this workload without changing the interpreter.
Show answer
Only the thread holding the GIL can execute Python bytecode, and a pure-Python CPU-bound function never blocks, so the threads take turns on the one lock (switching about every 5 ms) instead of running on separate cores. The process therefore uses about one core's worth of CPU, and the switching adds a little overhead. To get parallelism, use multiprocessing or ProcessPoolExecutor (one interpreter and GIL per process), or move the hot loop into a native extension that releases the GIL, such as NumPy operations or Cython/C/Rust code.
Exercise
A web service runs a background thread that does heavy pure-Python computation. Another thread handles short network requests and has become slow, even though the network is fast. What is this effect called, and what does sys.setswitchinterval change about it?
Show answer
This is the convoy effect. The I/O thread finishes each wait, requests the GIL, and must wait for the compute thread to release it, which can take up to one switch interval each time. Lowering the interval lets the I/O thread get the GIL sooner (lower latency) but increases switching overhead. It does not increase the amount of computation done per second.