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 in standard CPython. Here you will see how that rule changes the results for two kinds of work.
The rule that decides everything
A thread must hold the GIL to execute Python bytecode. It gives the GIL up in two situations:
- It blocks on something outside Python, such as
time.sleep, a socket read, or a file read. - The interpreter asks it to yield. By default a running thread is asked to yield after about 5 milliseconds (see
sys.getswitchinterval()).
So threads take turns on the GIL. Whether that costs you time depends on how much of each thread's life is spent waiting and how much is spent computing.
I/O-bound threads: the GIL barely matters
An I/O-bound thread spends most of its time waiting. While it waits, it does not hold the GIL, so other threads run. Five one-second waits overlap:
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")This prints [0, 2, 4, 6, 8] after about 1.0 seconds. Run sequentially, the same work takes about 5 seconds. Real network and disk calls behave the same way, because the standard library releases the GIL around the blocking system call.
CPU-bound threads: the GIL is the bottleneck
A CPU-bound thread never waits, so it keeps wanting the GIL. Four such threads cannot run at the same moment, and adding threads adds switching overhead. This program times the same pure-Python loop with threads and with processes:
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def count_down(n):
while n > 0:
n -= 1
def run(executor_cls):
start = time.perf_counter()
with executor_cls(max_workers=4) as pool:
list(pool.map(count_down, [10_000_000] * 4))
return time.perf_counter() - start
if __name__ == "__main__":
print("threads: ", round(run(ThreadPoolExecutor), 2))
print("processes:", round(run(ProcessPoolExecutor), 2))On a standard GIL build with several cores, the thread time is roughly the same as running the four jobs one after another, and sometimes worse. The process time is usually lower, because each process has its own interpreter and its own GIL. Exact numbers depend on your machine. Processes also pay a startup cost, so very small jobs may not benefit.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using threads to speed up a numeric loop in pure Python | No speedup, possibly a slowdown | Use processes, or a native library that releases the GIL |
| Assuming the GIL makes shared data safe | `counter += 1` is several bytecode steps, so updates can still be lost | Protect shared state with a `threading.Lock` |
| Using processes for tiny, quick tasks | Startup and pickling cost more than the work | Batch the work, or use threads |
| Forgetting the `__main__` guard with processes | Child processes re-import the script and can fail or spawn recursively under `spawn` | Wrap the entry point in `if __name__ == "__main__":` |
Mixed workloads
Real programs often mix both kinds of work. A common split is to use threads for the waiting parts, such as fetching pages, and a process pool for the heavy computation on the results. Chapter by chapter, the next topics cover how processes start and how they exchange data.
Exercise
You have a script that downloads 200 small files and then computes a checksum of each file in pure Python. Which part benefits from a ThreadPoolExecutor on a standard GIL build, and which part needs a ProcessPoolExecutor to use several cores? Explain why.
Show answer
The downloads benefit from threads, because each thread releases the GIL while it waits on the network, so the waits overlap. The pure-Python checksum is CPU-bound, so threads would take turns on the GIL and give no speedup. A ProcessPoolExecutor gives each worker its own interpreter and GIL, so the checksums run in parallel on separate cores.