Sub topic 12
Threads, processes, and the GIL: what actually speeds up
This chapter assumes you can write Python functions and loops and run scripts from a terminal. It also assumes you have profiled a program and found a bottleneck. Concurrency is a fix to try after you have fixed the algorithm and measured the result.
The GIL in one paragraph
CPython has a global interpreter lock (GIL). Only one thread runs Python bytecode at a time within a process. Threads still help when they spend their time waiting, because a waiting thread releases the lock. They do not help when every thread is computing in pure Python.
This gives two kinds of bottleneck:
- I/O-bound: the program waits on a network, a disk, or a database. Threads help.
- CPU-bound: the program spends its time computing in Python. Processes help.
Your profile tells you which one you have. If most time sits in socket or read calls, it is I/O-bound. If it sits in your own functions, it is CPU-bound.
Threads for waiting work
The example below simulates ten one-second waits. time.sleep releases the GIL, as real network calls do.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(_):
time.sleep(1)
return "done"
start = time.perf_counter()
for i in range(10):
fetch(i)
print(f"sequential: {time.perf_counter() - start:.2f}s")
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=10) as pool:
list(pool.map(fetch, range(10)))
print(f"threaded: {time.perf_counter() - start:.2f}s")The sequential run takes about 10 seconds. The threaded run takes about 1 second, because all ten waits overlap.
Processes for computing work
Each process has its own interpreter and its own GIL, so processes can use several CPU cores. The next example runs the same CPU-bound function with threads and with processes.
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def burn(n):
total = 0
for i in range(n):
total += i * i
return total
def run(executor_cls):
start = time.perf_counter()
with executor_cls(max_workers=4) as pool:
list(pool.map(burn, [3_000_000] * 4))
return time.perf_counter() - start
if __name__ == "__main__":
print(f"threads: {run(ThreadPoolExecutor):.2f}s")
print(f"processes: {run(ProcessPoolExecutor):.2f}s")On a machine with four or more cores, the thread version takes about as long as running the four tasks one after another. The process version is closer to the time of a single task. The if __name__ == "__main__": guard is required. Without it, worker processes started with the spawn method re-import the module and try to start more workers.
Costs of processes
Processes are not free. Check these before you adopt them:
- Starting a process takes milliseconds to tens of milliseconds.
- Arguments and results are pickled and copied between processes. Large objects make this slow.
- Each task should do enough work to outweigh that overhead. Many tiny tasks can run slower than a plain loop.
- Functions passed to a pool must be picklable, so define them at module level.
Common errors
- Using threads for CPU-bound Python code. It adds overhead and gives no speedup.
- Skipping the measurement. Time the sequential version first and compare it with the parallel one.
- Expecting linear scaling. Four workers rarely give a 4x speedup. Overhead and shared resources reduce it.
- Forgetting the main guard when you use processes.
Exercise
A script spends 90% of its time in a pure Python loop that computes a checksum for each of 200 large records. Should you try ThreadPoolExecutor or ProcessPoolExecutor first, and what should you check about the tasks?
Show answer
Try ProcessPoolExecutor first, because the work is CPU-bound Python and threads would share one GIL. Check that each task does enough work to outweigh process startup and pickling costs. For example, send each worker a batch of records instead of one tiny task, and time the result against the sequential version.
Exercise
Why does the ProcessPoolExecutor example need the if __name__ == "__main__": guard?
Show answer
With the spawn start method, each worker re-imports the main module. Without the guard, that import would run the pool-creating code again in every worker.