Python · Module 09: Concurrency, APIs & TestingTutorial 26 of 30

9.1 Multithreading, Multiprocessing & asyncio (The GIL Explained)

Make your Python apps blazingly fast! Understand the GIL with a kitchen analogy, know exactly when to pick threading vs. asyncio vs. multiprocessing, and write clean async/await code.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Concurrency vs. Parallelism & The GIL (Kitchen Analogy)

Imagine cooking pasta and chopping vegetables:

  • Concurrency (threading / asyncio): 1 chef puts water on the stove, and while waiting for it to boil (I/O wait), chops vegetables! Great for I/O-bound work (HTTP requests, DB queries, file downloads).
  • Parallelism (multiprocessing): 4 chefs working on 4 separate cutting boards at the exact same instant! Essential for CPU-bound work (image resizing, ML math, video encoding).

What is the GIL (Global Interpreter Lock)? In standard CPython, only one thread can execute Python bytecode at a time to protect reference counts. That means threading speeds up I/O waiting (because threads release the GIL while waiting on network/disk), whereas multiprocessing spawns separate Python processes to bypass the GIL and use all CPU cores!

Visual: Picking the Right Python Concurrency Tool (I/O-Bound vs. CPU-Bound)
threadingI/O-BoundBlocking APIs / DiskShares 1 GIL; switches while waitingasyncio (async/await)High I/O Scale10,000+ HTTP / DB calls1 thread + Event Loop (zero lock pain)multiprocessingCPU-BoundVideo / ML / Heavy MathSeparate processes → Bypasses GIL!

2. Cleanest Ways to Write Each One

1) ThreadPoolExecutor (Easiest for Blocking HTTP/Disk I/O)

PYTHON
from concurrent.futures import ThreadPoolExecutor

def fetch_status(url):
    return f"{url} -> 200 OK"

urls = ["https://a.com", "https://b.com", "https://c.com"]
with ThreadPoolExecutor(max_workers=3) as pool:
    results = list(pool.map(fetch_status, urls))

2) ProcessPoolExecutor (For Heavy CPU Math Across Cores)

PYTHON
from concurrent.futures import ProcessPoolExecutor

def heavy_square(n):
    return sum(i * i for i in range(n))

if __name__ == "__main__":      # Required for multiprocessing on Windows/macOS!
    with ProcessPoolExecutor() as pool:
        print(list(pool.map(heavy_square, [200_000, 300_000])))

3) Modern asyncio (async def + await + asyncio.gather)

PYTHON
import asyncio

async def fetch_data(name, delay):
    await asyncio.sleep(delay)    # Yields control back to the Event Loop!
    return f"{name} ready"

async def main():
    # Runs BOTH concurrently -> takes ~1.0s total instead of 2.0s!
    r1, r2 = await asyncio.gather(
        fetch_data("Orders", 1.0),
        fetch_data("Profile", 1.0),
    )
    print(r1, "|", r2)

asyncio.run(main())

Beginner Trap: Inside an async def function, NEVER call blocking time.sleep(2) — it freezes the entire event loop! Always use await asyncio.sleep(2) (and httpx / aiohttp instead of blocking requests).


3. Interactive Trace: asyncio.gather() Overlapping Wait Times

Tracing Concurrent async/await Tasks
Interactive Line-by-Line Execution Trace · Step 1 of 4
1async def fetch(name):
2 await asyncio.sleep(1)
3 return f"{name}: OK"
4→res = await asyncio.gather(fetch("A"), fetch("B"))
5print(res)
Variables in Memory
event_loopschedules fetch('A') & fetch('B')loop
Console Output
(nothing printed yet)
What just happened: asyncio.gather schedules BOTH coroutines on the single-threaded event loop at t = 0.0s.

Quick Quiz: Module 9.1 — Concurrency & The GIL

Q1.You need to compress 500 large images using heavy CPU math on an 8-core machine. Which tool should you pick?
Q2.Why should you avoid calling `time.sleep(5)` inside an `async def` coroutine?
Q3.Why does `threading` still speed up downloading 50 web pages despite the GIL?

Keep Exploring: Related Lessons & Tools

All Courses →