Sub topic 12
Threads, Processes, and the GIL: What Actually Speeds Up
This chapter assumes you can write Python functions and loops, run scripts from a terminal, and read cProfile output. It also assumes you have already profiled your program and fixed the algorithm and data structures. Parallelism comes after those steps, because a better algorithm usually beats extra workers and costs less to maintain.
Why parallelism is not automatic
Running work on several workers only helps if the bottleneck is the kind of work the workers can overlap. In CPython (the standard Python interpreter), the answer depends on the Global Interpreter Lock, or GIL.
The GIL is a lock inside the interpreter. Only one thread at a time can execute Python bytecode in a single process. Threads still exist and still take turns, but they do not run Python code at the same moment on different cores.
This gives a simple rule:
- If a program waits on something outside Python (network, disk, a database), threads can help. A waiting thread releases the GIL, so another thread can run.
- If a program spends its time computing in Python code, threads do not help. Processes can, because each process has its own interpreter and its own GIL.
Your profile tells you which case you are in. If the slow functions spend their time in time.sleep, socket reads, requests.get, or file reads, the work is I/O-bound. If the time is in your own arithmetic and loops, the work is CPU-bound.
Measuring the effect of threads on I/O-bound work
Do not trust the rule on faith. Measure it. The next script simulates ten slow requests with time.sleep, which releases the GIL just as a real network wait does.
import time
from concurrent.futures import ThreadPoolExecutor
def fake_request(n):
time.sleep(0.5)
return n
def run_serial():
return [fake_request(i) for i in range(10)]
def run_threaded():
with ThreadPoolExecutor(max_workers=10) as pool:
return list(pool.map(fake_request, range(10)))
start = time.perf_counter()
run_serial()
print(f"serial: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
run_threaded()
print(f"threaded: {time.perf_counter() - start:.2f}s")The serial run takes about 5 seconds. The threaded run takes about 0.5 seconds, because all ten waits overlap. The speedup is close to the number of workers because the workers do almost no computing.
ThreadPoolExecutor comes from concurrent.futures. It is usually a better choice than creating threading.Thread objects by hand, because it manages a pool of workers, collects return values, and re-raises exceptions in the caller.
Measuring the effect of threads on CPU-bound work
Now try the same pattern with a function that computes in pure Python.
import time
from concurrent.futures import ThreadPoolExecutor
def count_down(n):
while n > 0:
n -= 1
def run_serial(jobs, size):
for _ in range(jobs):
count_down(size)
def run_threaded(jobs, size):
with ThreadPoolExecutor(max_workers=jobs) as pool:
list(pool.map(count_down, [size] * jobs))
JOBS = 4
SIZE = 5_000_000
start = time.perf_counter()
run_serial(JOBS, SIZE)
print(f"serial: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
run_threaded(JOBS, SIZE)
print(f"threaded: {time.perf_counter() - start:.2f}s")On a standard CPython build, the threaded time is about the same as the serial time, and it is sometimes slower. The threads fight over the GIL and add switching overhead. Four threads on four cores do not give a fourfold speedup here.
Processes for CPU-bound work
A process pool starts several separate Python processes. Each has its own GIL, so the operating system can run them on different cores at the same time. This is the standard fix for CPU-bound pure Python.
import time
from concurrent.futures import ProcessPoolExecutor
def count_down(n):
while n > 0:
n -= 1
def run_serial(jobs, size):
for _ in range(jobs):
count_down(size)
def run_processes(jobs, size):
with ProcessPoolExecutor(max_workers=jobs) as pool:
list(pool.map(count_down, [size] * jobs))
if __name__ == "__main__":
JOBS = 4
SIZE = 5_000_000
start = time.perf_counter()
run_serial(JOBS, SIZE)
print(f"serial: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
run_processes(JOBS, SIZE)
print(f"processes: {time.perf_counter() - start:.2f}s")On a machine with at least four free cores, the process version typically finishes in a bit over a quarter of the serial time. The result is never a perfect fourfold gain, because starting processes and moving data costs time.
The if __name__ == "__main__": guard is required. On Windows and macOS, child processes start by importing your module. Without the guard, each child would try to start more children, and the program fails with an error or loops.
What processes cost
Processes are not free. Four costs decide whether they pay off:
- Startup. Each worker is a new interpreter. This takes tens of milliseconds or more, depending on the platform and the imports.
- Serialization. Arguments and results travel between processes through
pickle. Large arguments are copied and encoded, and this can cost more than the computation. - Memory. Each process holds its own copy of the data it uses. Ten workers can use roughly ten times the memory.
- Shared state. Workers cannot simply modify a shared list or dict. Changes made in a child process are not visible in the parent.
For this reason, give each task a large amount of work. Sending a million tiny tasks to a pool is often slower than a plain loop. The chunksize argument of pool.map groups items into batches and reduces the per-item overhead:
from multiprocessing import Pool
def square(n):
return n * n
if __name__ == "__main__":
with Pool() as pool:
results = pool.map(square, range(10), chunksize=2)
print(results)Here square is so cheap that a pool is the wrong tool for it in real code. The example only shows the syntax. In your own code, use a pool when each task takes at least several milliseconds.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| Threads give no speedup on a computation | CPU-bound pure Python, limited by the GIL | Use processes, or vectorize |
| Process pool is slower than the loop | Tasks too small, or large data is pickled for each task | Batch the work, raise `chunksize`, pass less data |
| `RuntimeError` about starting a new process before the current one finishes bootstrapping | Missing `if __name__ == "__main__":` guard | Add the guard |
| `PicklingError` or `AttributeError: Can't pickle local object` | Worker function is a lambda or nested function | Define the function at module top level |
| Results differ between runs, or counters are wrong | Threads updating shared data without a lock | Return values instead of mutating shared state, or use `threading.Lock` |
| Speedup stops growing after a few workers | Fewer physical cores than workers, or a shared resource is saturated | Check `os.cpu_count()` and measure with different worker counts |
Libraries that release the GIL
The GIL rule applies to Python bytecode. Many C extensions release the GIL while they do long computations. NumPy does this for many array operations, and so do hashlib for large inputs, zlib compression, and some image and database libraries.
In those cases threads can speed up CPU-bound work, and they avoid the pickling and memory costs of processes. Whether a specific function releases the GIL depends on the library and the version, so measure it. Do not assume.
If your hot loop can be replaced with a single NumPy expression, as in the vectorization chapter, that is usually simpler and faster than any form of parallelism.
Free-threaded Python
Recent CPython releases (3.13 and later) include an experimental free-threaded build that runs without the GIL. In that build, threads can run Python code on multiple cores. It is a separate build, not the default one, and some extension modules do not yet support it. The advice in this chapter, which is to measure first, is the same for that build. Check your version and build before you rely on either behavior.
Choosing a tool
Use the profile and the shape of the work to choose:
- Waiting on many network or disk operations:
ThreadPoolExecutor, orasyncioif the libraries you use support it. - Pure Python computation split into large independent pieces:
ProcessPoolExecutor. - Numeric loops over arrays: NumPy vectorization first, then threads if the library releases the GIL.
- A tight loop that cannot be split: a better algorithm, or native code, covered in a later chapter.
Always compare against a serial baseline. Use time.perf_counter around the whole operation, run it several times, and note the worker count and machine. A parallel version that is only slightly faster, but adds pickling errors and harder debugging, may not be worth keeping.
Exercise
A script downloads 200 small files over HTTP, then computes a SHA-256 hash of each in pure Python loops written by hand. The profile shows 90% of the time in the download function, which spends it waiting on the network. Which pool do you try first, and why would a process pool be a poor first choice?
Show answer
Try a ThreadPoolExecutor first. The download time is spent waiting, and a waiting thread releases the GIL, so the waits overlap. A process pool would add startup time, pickling, and extra memory without addressing the real cause, since the work is I/O-bound and not limited by the GIL.
Exercise
You run a four-worker ProcessPoolExecutor over 100,000 tasks that each add two numbers. It is slower than a for loop. Name two changes that could help.
Show answer
Increase the work per task, for example by passing each worker a chunk of many numbers instead of one pair, or pass chunksize to pool.map so items are batched. You could also drop the pool entirely, because the per-task work is smaller than the cost of pickling and sending it. A NumPy array addition would likely beat both.