Sub topic 9
Choosing between threads, processes, and asyncio
This chapter assumes you know the difference between I/O-bound and CPU-bound work, what the GIL (Global Interpreter Lock) does, and how to use concurrent.futures. Here you turn that knowledge into a decision, then check the decision by measuring.
Start with the bottleneck
Do not pick a model by habit. Ask what the program spends its time doing.
- Waiting on the network, disk, or a database. The CPU is idle, so the goal is to overlap the waits. Threads or asyncio fit.
- Computing in pure Python. The CPU is busy. On a standard GIL build, only processes use several cores.
- Computing inside a native library. Some libraries release the GIL while they work, so threads can run in parallel. Check the library's documentation.
Comparing the three models
| Model | Best for | Main cost | Shared memory |
|---|---|---|---|
| Threads | Blocking I/O, GIL-releasing native code | Locks needed for shared state | Yes |
| Processes | Pure-Python CPU work | Startup time, pickling of arguments and results | No |
| asyncio | Very many concurrent I/O tasks | Code must use `async`/`await` and async libraries | Yes (one thread) |
Threads are the easiest change to existing blocking code. Processes give real parallelism but make you pay to move data. asyncio scales to many more simultaneous tasks than threads, but one blocking call stalls every task on the event loop.
Measure before you commit
A short benchmark settles most arguments. The script below runs the same pool code against one waiting task and one computing task.
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def wait(_):
time.sleep(0.5) # stands in for I/O
def crunch(n):
return sum(i * i for i in range(n)) # pure-Python CPU work
def timed(executor_cls, fn, args):
start = time.perf_counter()
with executor_cls(max_workers=4) as pool:
list(pool.map(fn, args))
return round(time.perf_counter() - start, 2)
if __name__ == "__main__":
waits = range(4)
jobs = [3_000_000] * 4
print("wait threads: ", timed(ThreadPoolExecutor, wait, waits))
print("wait processes:", timed(ProcessPoolExecutor, wait, waits))
print("crunch threads: ", timed(ThreadPoolExecutor, crunch, jobs))
print("crunch processes:", timed(ProcessPoolExecutor, crunch, jobs))On a multi-core machine with a standard build, expect these patterns:
- The
waitruns take about 0.5 seconds with either pool, because the sleeping threads release the GIL. Processes add startup overhead for no gain. - The
crunchrun with threads takes roughly the sum of all four jobs, because the GIL lets one thread run Python bytecode at a time. - The
crunchrun with processes is faster, up to about the number of cores.
Because ThreadPoolExecutor and ProcessPoolExecutor share one interface, switching models is a one-word change. That makes experiments cheap.
Common mistakes
- Using processes for I/O. You pay for startup and pickling and gain nothing over threads.
- Using threads for pure-Python number crunching. The code may even run slower than the sequential version, because of lock contention.
- Calling blocking code inside
async def.time.sleep()or a synchronous HTTP call freezes the whole event loop. Useawait asyncio.sleep(), an async library, orasyncio.to_thread(). - Setting the worker count by guesswork. For CPU-bound pools, start near
os.cpu_count(). For I/O pools, test larger numbers, because the limit is the remote service rather than your cores. - Trusting a benchmark on a single run. Repeat it, and run it on the machine that will host the program.
Exercise
A script fetches 2,000 web pages using the requests library, which blocks on each call, and then parses each page with a pure-Python parser that takes about 200 ms per page. Which model would you use for each stage, and how would you confirm the choice?
Show answer
Use threads (or asyncio with an async HTTP client) for fetching, because the time is spent waiting on the network. Use a process pool for parsing, because pure-Python parsing is CPU-bound and the GIL prevents threads from using several cores. Confirm by timing each stage with both ThreadPoolExecutor and ProcessPoolExecutor on a realistic sample, as in the benchmark above. Because each parse takes 200 ms, that is enough work to cover pickling and process startup.