Lesson 6 of 9 · 26m
Threading, Multiprocessing, and asyncio: Pick by Waiting or Working
The GIL decision tree: threads and asyncio for I/O-bound waiting, processes or native extensions for CPU-bound work, and the hidden costs of each.
Python concurrency advice fails when it starts with tools instead of workload. The useful question is not "threads or processes?" It is: is the program waiting, or is it computing? If it is waiting on sockets, disks, databases, or subprocesses, concurrency is about overlapping latency. If it is burning CPU in Python bytecode, the standard GIL means threads mostly take turns.
The simple decision tree
- Network/database/file wait, many connections:
asyncioor threads. - Blocking third-party library, moderate number of tasks: threads.
- CPU-bound pure Python:
multiprocessingor a native extension that releases the GIL. - CPU-bound NumPy/native work: test threads; many native kernels release the GIL.
- Need shared mutable Python objects across workers: stop and redesign the data flow.
Threads are cheap to write and easy to misuse
from concurrent.futures import ThreadPoolExecutor
urls = [...]
def fetch(url):
return client.get(url, timeout=10).status_code
with ThreadPoolExecutor(max_workers=16) as pool:
statuses = list(pool.map(fetch, urls))Threads shine when the underlying call releases the GIL — socket I/O and many C extensions do. They fall apart when workers mutate shared Python state or when the payload is CPU-heavy. Locks do not make bad ownership good; they make it serialized and harder to reason about.
Processes buy isolation at serialization cost
from concurrent.futures import ProcessPoolExecutor
def render_chunk(chunk):
return [render(item) for item in chunk]
with ProcessPoolExecutor(max_workers=8) as pool:
pieces = pool.map(render_chunk, chunks, chunksize=4)Every task argument and return value must cross process boundaries, normally by pickling. Large objects can make the "parallel" program slower than the serial one. Chunk work deliberately, keep payloads small, and initialize expensive read-only resources once per worker when possible.
On Linux, fork is fast but copies file descriptors and can interact badly with threads and native libraries. spawn is cleaner and slower. Choose the start method explicitly for services where correctness matters more than startup convenience.
asyncio is one thread doing disciplined waiting
import asyncio
sem = asyncio.Semaphore(50)
async def one(url):
async with sem:
return await fetch(url)
async def fetch_all(urls):
return await asyncio.gather(*(one(u) for u in urls))The mental model is cooperative: tasks yield at await. A CPU-heavy or blocking call inside a coroutine stalls the whole event loop. Use asyncio.to_thread for unavoidable blocking work, or move true CPU work out of the process.
Field notes
- More workers than cores does not speed CPU-bound work; it adds context switches and memory.
- Set timeouts and bounds. A thread pool with unbounded queueing is a latency amplifier.
- Measure end-to-end throughput and tail latency, not just CPU utilization. Busy cores can still mean bad design.
- Log worker identity when debugging. Many "impossible" races become obvious when you see which process handled which item.
Was this lesson helpful?