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().

5 min readUpdated 2026-11-30
In This Lesson
  • 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:

python
# 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

Python Concurrency: Threads vs Processes vs asyncio

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

ToolConcurrency ModelBest WorkloadKey Tradeoff
ThreadPoolExecutorPreemptive 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 loop1,000+ concurrent network sockets, WebSockets, FastAPI/httpxTiny RAM per task; requires async-compatible libraries (httpx, aiofiles)
ProcessPoolExecutorSeparate OS processes (one GIL per core)Heavy CPU math, image/data crunchingTrue 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:

python
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:

  1. The event loop maintains a queue of ready tasks.
  2. A coroutine runs uninterrupted until it hits an await expression (like await asyncio.sleep(0.3) or await client.get(url)).
  3. At await, the coroutine yields control back to the event loop and says "wake me when this I/O is ready."
  4. Immediately, the event loop picks up the next waiting coroutine and runs it—meaning zero wasted idle time and zero race conditions between await points!
python
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())
2 Classic asyncio Bugs
  1. Calling blocking time.sleep() or requests.get() inside async def: Blocking calls never hit await, freezing the entire event loop so zero other coroutines can run! Always use await asyncio.sleep() and async clients (httpx.AsyncClient).
  2. Forgetting await: Calling fetch_course("sql", 0.1) without await does not run the function—it just returns an unused coroutine object and emits RuntimeWarning: coroutine was never awaited.

Try It Yourself in the Playground

Browser Playground Note for asyncio

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.

Python 3Try It Live: Concurrent asyncio.gather()
Output

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

Check Your Understanding

You need to compress 500 large PNG images in Python using heavy CPU calculations. Which concurrency tool gives true multi-core speedup?

Check Your Understanding

Why should you use await asyncio.sleep(1) instead of time.sleep(1) inside an async def coroutine?