Overview
Curated: · Written: · Reviewed:
Concurrency (GIL, Threading, Asyncio)
In one line
Threads overlap waiting, processes give CPU parallelism, and asyncio runs many cooperative I/O waits on one loop thread. Use threads or asyncio when work waits on I/O, and processes when pure-Python work must use several cores on a default build.
Key definitions
- GIL: the lock that lets one thread execute Python bytecode at a time in a default CPython build. It is released around blocking I/O and long native operations.
- Free-threaded build: optional CPython 3.14 build (python3.14t) with the GIL disabled. It is not the default and does not make your invariants safe.
- Invariant atomicity: a check-then-act sequence spans several operations and can interleave even under the GIL.
- Cooperative suspension: a task yields to the loop only at an await whose operation actually suspends.
- Cancellation: CancelledError delivered at the next suspension point. It is a request, not forced termination.
- Start method: spawn, fork or forkserver. It decides what a child process inherits.
How it works
- A thread blocked in a socket read releases the GIL, so another thread can run bytecode.
- Two threads running pure-Python loops take turns on the interpreter, so wall time stays near the serial total on a default build.
- A process has its own interpreter and memory. Arguments and results cross the boundary by pickling.
- A coroutine object does nothing until awaited or wrapped by create_task. The loop switches tasks only at await points.
When to use and when not to
| Model | Good for | Costs and limits |
|---|---|---|
| Threads | Blocking I/O with blocking libraries, bounded pool | GIL serializes bytecode; shared state needs locks |
| Processes | Pure-Python CPU work on several cores | Startup, pickling of arguments and results, no shared mutable state |
| asyncio | Many concurrent I/O waits with async libraries | One thread; a blocking or CPU call stalls every task |
| asyncio.to_thread | One bounded blocking call from async code | Cannot stop the thread; no CPU speedup on a default build |
Traps interviewers probe
- Assuming the GIL makes updates safe. The GIL does not make a check-then-act atomic. Fix: hold one lock across the whole sequence, for example
with lock: if counts[k] < LIMIT: counts[k] += 1. - Expecting threads to speed up CPU loops. Fix: use ProcessPoolExecutor with a module-level worker and batched items, or a verified free-threaded build whose dependencies are tested under it.
- Discarding the create_task reference. The task can outlive the request and its exception goes unobserved. Fix: use TaskGroup for scoped children, or keep references and add a completion callback.
- Reading a timeout as proof of no side effect. A timeout only ends the wait. Fix: make the operation idempotent, or reconcile its outcome before retrying.
- Expecting a child process to mutate the parent's list. The child gets a copy. Fix: return results from the worker, or send them through a Queue.
Interview tips
Open by classifying the work: does it wait or compute, and does it share mutable state? Then name the model and its failure boundary.
Expected follow-ups:
- Why does a free-threaded build still need locks?
- Why does to_thread not make a pure-Python loop faster on a default build?
- What breaks if a child under spawn relies on inherited globals?
- How do you bound a pool, and what happens when a worker dies?
30-second outline:
- Threads share one interpreter, so the GIL lets only one thread run bytecode at a time on a default build. Blocking I/O still overlaps because the GIL is released during the wait.
- For CPU parallelism I use processes, which cost startup and pickling but give each worker its own interpreter.
- For many async I/O calls I use asyncio on one loop, with bounded to_thread for any blocking call.
- Shared invariants get a lock across the whole check-then-act, and timeouts are backed by idempotency.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.