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.
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!
2. Cleanest Ways to Write Each One
1) ThreadPoolExecutor (Easiest for Blocking HTTP/Disk I/O)
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)
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)
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 deffunction, NEVER call blockingtime.sleep(2)— it freezes the entire event loop! Always useawait asyncio.sleep(2)(andhttpx/aiohttpinstead of blockingrequests).
3. Interactive Trace: asyncio.gather() Overlapping Wait Times
Quick Quiz: Module 9.1 — Concurrency & The GIL
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.