Sub topic 6
What the GIL means for I/O-bound and CPU-bound threads
This chapter assumes you can start threads with threading or ThreadPoolExecutor. It also assumes you know the Global Interpreter Lock (GIL) lets only one thread run Python bytecode at a time, and that you can tell I/O-bound work from CPU-bound work. Here we connect those ideas: what the GIL does to each kind of workload, why, and how to see it in your own measurements. The behavior described is for the standard CPython build, which has the GIL.
The rule in one sentence
In a standard CPython build, threads run Python code one at a time, but a thread that is waiting does not hold the GIL. So threads overlap waiting, and they do not overlap computing.
That gives two outcomes:
| Workload | What threads do | Typical result |
|---|---|---|
| I/O-bound (network, disk, `sleep`, database calls) | Waiting periods overlap | Close to a linear speedup, up to the point where the remote side or the OS becomes the limit |
| CPU-bound pure Python (loops, parsing, arithmetic) | Take turns holding the GIL | No speedup, often slightly slower |
How a thread gives up the GIL
A thread holding the GIL releases it in two situations.
- It blocks. CPython's standard-library wrappers around blocking operations release the GIL before waiting and reacquire it afterward. This covers
time.sleep, socket reads and writes, file reads and writes,subprocesswaits,lock.acquire, and mostselectcalls. - It is asked to yield. If another thread wants the GIL and the holder has run for a while without releasing it, the holder is forced to drop it at the next safe point between bytecode instructions. The wait is the switch interval.
You can read the switch interval:
import sys
print(sys.getswitchinterval()) # 0.005 seconds by defaultThe 5 ms default is a request timeout, not a time slice. A waiting thread asks for the GIL. If the holder has not released it within the interval, the holder is told to release it. The OS scheduler then decides which waiting thread runs next, and the GIL does not guarantee fairness.
I/O-bound work: threads help
The next script runs five tasks that each wait one second. The time.sleep call stands in for waiting on a network response.
import time
from concurrent.futures import ThreadPoolExecutor
def fake_download(n):
time.sleep(1) # stands in for waiting on the network
return n * 2
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(fake_download, range(5)))
print(results, f"{time.perf_counter() - start:.1f}s")Run sequentially, this would take about 5 seconds. With five threads it takes about 1.0 second, and the output looks like [0, 2, 4, 6, 8] 1.0s. While one thread sleeps, it does not hold the GIL, so the other four can start their own waits immediately.
The time a real I/O task spends in Python code (building a request, parsing a response) still needs the GIL. That time is usually small compared with the wait, which is why the speedup is large. If the Python part grows, for example when you parse large JSON responses, the speedup shrinks, because that parsing is CPU-bound and serialized.
Limits of the I/O speedup
- Worker count. More threads help only while there are more waits to overlap. Beyond the number of concurrent requests the server or network allows, extra threads add overhead and no speed.
- Rate limits and connection limits. A thread pool of 200 against an API that allows 10 concurrent requests gets throttled or blocked.
- Libraries that do not release the GIL while waiting. This is rare in widely used libraries, but a poorly written C extension can block while holding the GIL and stall every thread.
CPU-bound work: threads do not help
Now give threads work that never waits. The function below only decrements an integer, so it executes Python bytecode the whole time.
import time
from concurrent.futures import ThreadPoolExecutor
def count_down(n):
while n > 0:
n -= 1
N = 10_000_000
start = time.perf_counter()
for _ in range(4):
count_down(N)
sequential = time.perf_counter() - start
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(count_down, [N] * 4))
threaded = time.perf_counter() - start
print(f"sequential: {sequential:.2f}s")
print(f"4 threads: {threaded:.2f}s")On a standard build you should see the two times land close together, and the threaded one is often a bit slower. Exact numbers depend on your machine and Python version. A four-core laptop does not make four threads four times faster, because only one thread can execute bytecode at any moment. The extra time comes from threads contending for the GIL and from the operating system switching between them.
Why the GIL exists, briefly
CPython manages memory with reference counting. Every object carries a count of references to it, and the count changes constantly as code runs. If two threads updated a count at the same time without protection, the count could end up wrong, causing leaks or freeing an object that is still in use. A single global lock is a simple way to make all of that safe, and it also keeps single-threaded programs fast because there is no per-object locking cost.
Mixed workloads and latency
Real programs often mix both kinds of work in one process. Two effects matter.
- A CPU-bound thread delays I/O threads. When data arrives for an I/O thread, it must reacquire the GIL before it can continue. If another thread is crunching numbers, the I/O thread waits for the switch interval (about 5 ms) at minimum before it can force a handoff. Each wake-up can pay this cost, so latency rises even though throughput looks fine.
- Throughput drops when threads thrash. A thread that releases the GIL for very short operations, such as many small reads, has to fight for it each time it returns.
The practical consequence is that a web server or a GUI doing heavy computation in a background thread can feel sluggish. Moving the computation to a separate process, which has its own GIL, removes the contention.
Things the GIL does not do
- It does not make your code thread-safe. The GIL protects the interpreter's internal state. An operation like
counter += 1is several bytecode steps, and a thread switch can happen between them. You still need locks around shared data, as covered earlier. - It does not prevent parallel waiting. Many threads can be blocked in system calls at the same moment, which is exactly why I/O threads scale.
- It does not apply to every library. Some native extensions release the GIL while they compute, so threads can run in parallel inside them. A later chapter covers this.
- It is not part of the Python language. It is a property of the CPython implementation. Builds without it exist, described in the final chapter.
Diagnosing which case you are in
A quick test separates the two situations.
- Run the task sequentially and note the wall-clock time.
- Run it in a thread pool and note the time.
- Compare. If threads cut the time roughly in proportion to the worker count, the work is I/O-bound. If the times are about equal, the work is CPU-bound or dominated by something that holds the GIL.
You can also compare CPU time with wall time using time.process_time() against time.perf_counter(). If the process's CPU time is close to the wall time, the program is computing nearly all the time. If CPU time is far lower than wall time, the program is mostly waiting.
import time
def profile(func, *args):
wall = time.perf_counter()
cpu = time.process_time()
func(*args)
return time.perf_counter() - wall, time.process_time() - cpu
wall, cpu = profile(time.sleep, 1)
print(f"wall {wall:.2f}s, cpu {cpu:.2f}s") # wall ~1.00s, cpu ~0.00sA ratio of CPU to wall time near zero points to I/O-bound work, where threads (or asyncio) are the right tool. A ratio near one points to CPU-bound work, where you need processes or a library that releases the GIL.
Common mistakes
- Using threads to speed up a numeric loop. The loop stays serial and gains thread overhead.
- Assuming more threads is always faster for I/O. Past the concurrency the remote service allows, you gain nothing.
- Timing a single run. Timings vary between runs because of OS scheduling. Repeat the measurement and compare medians.
- Testing with tiny inputs. Thread start-up cost can dominate a task that lasts a millisecond, hiding the real behavior.
Exercise
A script downloads 100 small JSON files with a 20-thread pool and then parses each one with a heavy pure-Python function. Downloading got about 15 times faster after adding threads, but the parsing step did not get faster at all. Explain both results in terms of the GIL.
Show answer
While a thread waits on the network it has released the GIL, so up to 20 downloads wait at once and the download phase speeds up nearly in proportion to the number of threads. The parsing function is pure Python and runs bytecode continuously, so only the thread holding the GIL makes progress and the others wait for it. Parsing therefore takes about the same total time as running it sequentially. To speed up parsing, move it to a process pool or use a library that releases the GIL during computation.
Exercise
You measure a function and find processtime() is 0.02 s while perfcounter() is 2.0 s for the same call. Would you reach for threads or processes to run many calls at once, and why?
Show answer
Threads. The CPU time is about 1% of the wall time, so the function spends nearly all its time waiting, which means it is I/O-bound. Waiting threads release the GIL, so many calls can overlap in a thread pool, and processes would add start-up and pickling cost without a benefit.