5. Concurrency, Testing & Code Quality
Concurrency Demystified: Threading, Multiprocessing & asyncio
Know exactly when to use threads, processes, or async/await in Python: understand I/O-bound vs CPU-bound work, the GIL, ThreadPoolExecutor, and concurrent asyncio.gather().
- Distinguish I/O-bound tasks (waiting) from CPU-bound tasks (computing)
- Understand why Python's GIL affects threads vs multiple processes
- Run concurrent async coroutines safely with async def, await, and asyncio.gather()
Imagine fetching data from 20 web APIs. Doing them one by one—waiting 200ms per response—takes 4 seconds. Doing them concurrently takes ~200ms total!
In Python, there are three main concurrency tools—and picking the right one starts with one simple question: Is your code waiting (I/O-bound) or crunching numbers (CPU-bound)?
Why It Matters: Before vs After
Watch how asyncio.gather() collapses total wait time from the sum of all delays to the maximum delay:
# Before: sequential — waits 0.3s + 0.2s + 0.1s = 0.6s total
r1 = await fetch_course("python-fundamentals", 0.3)
r2 = await fetch_course("intermediate-python", 0.2)
r3 = await fetch_course("sql-databases", 0.1)
# After: concurrent — all 3 wait simultaneously (~0.3s total!)
r1, r2, r3 = await asyncio.gather(
fetch_course("python-fundamentals", 0.3),
fetch_course("intermediate-python", 0.2),
fetch_course("sql-databases", 0.1),
)1. Deep Mental Model: I/O-Bound vs CPU-Bound & The GIL
ThreadPoolExecutor
1 Process · N Threads · Shared GIL
Great for blocking I/O (requests, disk, sqlite3). Releases GIL while waiting.
asyncio Event Loop
1 Thread · Cooperative await
Best for 1,000+ concurrent network tasks (httpx.AsyncClient, FastAPI).
ProcessPoolExecutor
N Processes · Separate GILs
True multi-core CPU parallelism for heavy math, video/image encoding.
Pick ThreadPoolExecutor or asyncio for waiting (I/O-bound), and ProcessPoolExecutor to bypass the GIL for heavy math (CPU-bound).
- I/O-bound work spends most of its time waiting for networks, databases, or disks (API calls, file downloads, DB queries).
- CPU-bound work keeps the processor 100% busy (image resizing, cryptography, video encoding, heavy pure-Python math loops).
In standard CPython, the Global Interpreter Lock (GIL) allows only one thread inside a single Python process to execute Python bytecode at a given instant (protecting reference counts in memory).
- Threads still crush I/O-bound workloads, because Python releases the GIL whenever a thread blocks on a socket, disk read, or
time.sleep()—letting other threads run while it waits! - Threads do NOT speed up CPU-bound Python bytecode, because threads take turns holding the single GIL on one core. For true multi-core CPU parallelism, use
ProcessPoolExecutor, which spawns separate OS processes—each with its own Python interpreter, memory space, and GIL!
Decision Table: ThreadPoolExecutor vs ProcessPoolExecutor vs asyncio
| Tool | Concurrency Model | Best Workload | Key Tradeoff |
|---|---|---|---|
ThreadPoolExecutor | Preemptive OS threads (shared memory, GIL) | 10–100 blocking I/O calls (requests, sqlite3, file I/O) | Easy drop-in for sync libraries; thread context-switching overhead at 1,000s |
asyncio (async/await) | Single-threaded cooperative event loop | 1,000+ concurrent network sockets, WebSockets, FastAPI/httpx | Tiny RAM per task; requires async-compatible libraries (httpx, aiofiles) |
ProcessPoolExecutor | Separate OS processes (one GIL per core) | Heavy CPU math, image/data crunching | True multi-core speedup; inputs/outputs must be picklable across processes |
2. Clean Thread & Process Pools (concurrent.futures)
Whenever you have a normal synchronous function like fetch_status(site), ThreadPoolExecutor runs calls concurrently without managing raw Thread objects or locks manually:
from concurrent.futures import ThreadPoolExecutor
def fetch_status(site: str) -> str:
return f"{site}: 200 OK"
sites = ["api.yadavacademy.org", "cdn.yadavacademy.org", "docs.yadavacademy.org"]
with ThreadPoolExecutor(max_workers=3) as pool:
results = list(pool.map(fetch_status, sites))
print(results)(Need CPU parallelism instead? Swap ThreadPoolExecutor for ProcessPoolExecutor—the .map() and .submit() API is identical! Always place ProcessPoolExecutor calls inside if __name__ == "__main__": on Windows/macOS so child processes don't re-run top-level code.)
3. How the asyncio Event Loop Schedules Tasks
Unlike OS threads (where the OS kernel interrupts threads at any moment), asyncio runs cooperative multitasking inside a single thread:
- The event loop maintains a queue of ready tasks.
- A coroutine runs uninterrupted until it hits an
awaitexpression (likeawait asyncio.sleep(0.3)orawait client.get(url)). - At
await, the coroutine yields control back to the event loop and says "wake me when this I/O is ready." - Immediately, the event loop picks up the next waiting coroutine and runs it—meaning zero wasted idle time and zero race conditions between
awaitpoints!
import asyncio
async def fetch_course(slug: str, delay: float) -> str:
await asyncio.sleep(delay) # Suspension point: yields control to event loop!
return f"Loaded {slug}"
async def main():
# asyncio.gather() schedules all 3 coroutines concurrently on the event loop
results = await asyncio.gather(
fetch_course("python-fundamentals", 0.3),
fetch_course("intermediate-python", 0.2),
fetch_course("sql-databases", 0.1),
)
print(results)
if __name__ == "__main__":
asyncio.run(main())- Calling blocking
time.sleep()orrequests.get()insideasync def: Blocking calls never hitawait, freezing the entire event loop so zero other coroutines can run! Always useawait asyncio.sleep()and async clients (httpx.AsyncClient). - Forgetting
await: Callingfetch_course("sql", 0.1)withoutawaitdoes not run the function—it just returns an unused coroutine object and emitsRuntimeWarning: coroutine was never awaited.
Try It Yourself in the Playground
Because our interactive browser runtime (Pyodide) already runs an active event loop, use top-level await main() in the playground below—and asyncio.run(main()) when running .py files from your terminal.
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Create two async def tasks step_a() (waits 0.1s, returns "A") and step_b() (waits 0.15s, returns "B"), run both concurrently with asyncio.gather(), and print the returned list.
Quick Checkpoints
You need to compress 500 large PNG images in Python using heavy CPU calculations. Which concurrency tool gives true multi-core speedup?
Why should you use await asyncio.sleep(1) instead of time.sleep(1) inside an async def coroutine?