Concurrency & asyncio
Threads, processes and async in Python — choosing between threading, multiprocessing and asyncio, concurrent.futures, how the asyncio event loop and coroutines work, tasks and TaskGroups, timeouts, cancellation, and mixing sync and async code.
Python offers three concurrency models. Choosing correctly depends on whether your work is I/O-bound (waiting on networks and disks) or CPU-bound (computing), and on the GIL.
Choosing
| Model | Parallel CPU? | Best for | Scale |
|---|---|---|---|
| threading | No (GIL) — except in C extensions that release it | Blocking I/O with libraries that aren't async (requests, DB drivers) | Tens to hundreds of threads |
| multiprocessing | Yes — one interpreter per process | CPU-bound pure Python | ~Number of cores |
| asyncio | No (one thread) | High-concurrency I/O: thousands of sockets, HTTP clients/servers | Tens of thousands of tasks |
concurrent.futures: the easy interface
The same API for threads and processes:
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import requests
urls = [f"https://example.com/page/{i}" for i in range(50)]
# I/O-bound: threads
with ThreadPoolExecutor(max_workers=16) as pool:
futures = {pool.submit(requests.get, u, timeout=10): u for u in urls}
for fut in as_completed(futures): # results as they finish
url = futures[fut]
try:
print(url, fut.result().status_code)
except Exception as e:
print(url, "failed:", e)
# CPU-bound: processes (functions and arguments must be picklable)
def checksum(path): ...
if __name__ == "__main__": # required on Windows/macOS (spawn start method)
with ProcessPoolExecutor() as pool:
results = list(pool.map(checksum, paths, chunksize=16))Process pools pay for pickling arguments and results between processes, so give each task meaningful work (or use chunksize). Share large read-only data via memory-mapped files or multiprocessing.shared_memory.
threading essentials
import threading, queue
lock = threading.Lock()
with lock: # protect shared state
balance += amount
q: queue.Queue[str] = queue.Queue(maxsize=100) # thread-safe; bounded for backpressure
def worker():
while (item := q.get()) is not None: # None = shutdown signal
process(item)
q.task_done()
threads = [threading.Thread(target=worker, daemon=True) for _ in range(4)]
for t in threads: t.start()Other primitives: RLock (reentrant), Event, Condition, Semaphore, Barrier, and threading.local() for per-thread data.
asyncio: cooperative concurrency on one thread
asyncio runs many coroutines on a single thread, switching between them only at await points — when a coroutine waits for I/O, the event loop runs another one. It's the same idea as the JavaScript event loop (The event loop).
import asyncio
import httpx
async def fetch(client: httpx.AsyncClient, url: str) -> int:
resp = await client.get(url, timeout=10) # suspends here; other tasks run
return resp.status_code
async def main():
async with httpx.AsyncClient() as client:
codes = await asyncio.gather(*(fetch(client, u) for u in urls)) # run concurrently
print(codes)
asyncio.run(main()) # create the loop, run main, clean upHow it works
async defdefines a coroutine function; calling it returns a coroutine object — nothing runs yet.awaitsuspends the current coroutine until the awaited thing completes (a coroutine, a Task, or a Future).- The event loop keeps a queue of ready callbacks and uses the OS selector (epoll/kqueue/IOCP) to learn which sockets are ready. When data arrives, it resumes the coroutine that was waiting.
- Coroutines are built on generators:
awaitis essentiallyyield fromwith stricter rules (Iterators & generators).
Tasks: running things concurrently
await coro() runs sequentially. To run concurrently, wrap coroutines in Tasks:
async def main():
# Sequential: ~2 s
a = await fetch_a() # 1 s
b = await fetch_b() # 1 s
# Concurrent: ~1 s
task_a = asyncio.create_task(fetch_a()) # scheduled immediately
task_b = asyncio.create_task(fetch_b())
a, b = await task_a, await task_b
# Structured concurrency (3.11+): TaskGroup
async with asyncio.TaskGroup() as tg:
ta = tg.create_task(fetch_a())
tb = tg.create_task(fetch_b())
# here both are done; if one failed, the others were cancelled and an ExceptionGroup is raised
print(ta.result(), tb.result())Keep a reference to tasks you create with create_task — the loop only holds weak references, so an unreferenced task can be garbage-collected mid-flight.
Timeouts, cancellation and limits
async def main():
try:
async with asyncio.timeout(5): # 3.11+
data = await slow_operation()
except TimeoutError:
data = None
# Limit concurrency: at most 10 requests in flight
sem = asyncio.Semaphore(10)
async def limited(url):
async with sem:
return await fetch(client, url)
results = await asyncio.gather(*(limited(u) for u in urls), return_exceptions=True)
# Producer/consumer
q: asyncio.Queue[str] = asyncio.Queue(maxsize=100)Cancellation is delivered by raising asyncio.CancelledError inside the task at its current await. Clean up in finally, and re-raise it if you catch it.
The golden rule: never block the loop
Everything shares one thread. A blocking call freezes every task:
async def handler():
time.sleep(2) # ✗ blocks the whole event loop
requests.get(url) # ✗ blocking HTTP library
hashlib.pbkdf2_hmac(...) # ✗ long CPU work
await asyncio.sleep(2) # ✓
await client.get(url) # ✓ async library (httpx, aiohttp)
await asyncio.to_thread(blocking_function, arg) # ✓ run blocking code in a thread
await loop.run_in_executor(process_pool, cpu_heavy, arg) # ✓ CPU work in processesUse async-native libraries: httpx/aiohttp (HTTP), asyncpg/psycopg 3 (PostgreSQL), redis.asyncio, and frameworks like FastAPI, Starlette, aiohttp. Debug with asyncio.run(main(), debug=True), which warns about slow callbacks and never-awaited coroutines.
"Function colouring"
Async functions can only be awaited from async functions, so async tends to spread through a codebase. Plan the boundary: a sync program calls asyncio.run() once at the top; async code calls sync blocking code through asyncio.to_thread.
Comparison in one example
Download 100 URLs, each taking ~1 s of network wait:
| Approach | Time | Notes |
|---|---|---|
| Sequential | ~100 s | |
ThreadPoolExecutor(20) | ~5 s | Simple with blocking libraries |
asyncio + httpx, all at once | ~1 s | Lowest overhead; needs async libraries |
ProcessPoolExecutor | ~13 s on 8 cores | Wrong tool: overhead with no CPU benefit |
- I/O-bound: threads or asyncio. CPU-bound pure Python: processes (or free-threaded builds).
- concurrent.futures gives one API for thread and process pools.
- asyncio runs coroutines on one thread, switching only at await; the event loop multiplexes I/O.
- Use create_task / gather / TaskGroup for concurrency, asyncio.timeout for deadlines, Semaphore for limits.
- Never block the loop: use async libraries or asyncio.to_thread.
QWhen would you use asyncio vs threads vs multiprocessing?medium
For CPU-bound pure-Python work, use multiprocessing because each process has its own GIL and runs in parallel. For I/O-bound work, threads are easy with existing blocking libraries and handle moderate concurrency; asyncio handles very high concurrency (thousands of connections) with lower overhead but requires async-compatible libraries and care never to block the event loop.
QWhat's the difference between a coroutine and a task in asyncio?medium
A coroutine object is created by calling an async function; it does nothing until awaited or scheduled. A Task wraps a coroutine and schedules it on the event loop to run concurrently with other tasks; it's a Future that completes with the coroutine's result. Awaiting a coroutine directly runs it inline; creating tasks (create_task, gather, TaskGroup) runs them concurrently.