12.1 The GIL
The GIL is a mutex in CPython allowing only one thread to execute Python bytecode at a time, even on multi-core hardware — it exists because CPython’s reference counting isn’t thread-safe without it, and because many C extensions assume single-threaded execution.
WITH GIL: Thread1 ████░░░░████░░░░ Thread2 ░░░░████░░░░████ (only one runs Python bytecode at a time)
| Task Type | GIL Impact | Solution |
|---|---|---|
| CPU-bound | Severe — no parallelism, threading can even be slower | multiprocessing, ProcessPoolExecutor, C extensions |
| I/O-bound | Minimal — GIL released during I/O | threading or asyncio |
# Threaded CPU-bound work is NOT faster — often slower (lock contention overhead)
t1 = threading.Thread(target=cpu_bound_task, args=(50_000_000,))
t2 = threading.Thread(target=cpu_bound_task, args=(50_000_000,))
Python 3.13 introduces an experimental free-threaded build (--disable-gil, PEP 703) enabling true multi-threaded parallelism, but it remains opt-in and not yet the default.
12.2 Threading — I/O Concurrency
import threading
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
self._lock = threading.Lock()
def deposit(self, amount):
with self._lock: # Acquire, auto-release on exit
self.balance += amount
# RLock — reentrant, same thread can re-acquire
# Semaphore(n) — cap concurrent access to n
# Event — cross-thread signaling
# Condition — wait_for(predicate)
12.3 Multiprocessing — True Parallelism
import multiprocessing
def cpu_intensive(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
with multiprocessing.Pool(processes=4) as pool:
results = pool.map(cpu_intensive, [10_000_000] * 4) # True parallel — bypasses GIL
| Factor | Threading | Multiprocessing |
|---|---|---|
| Creation overhead | ~1ms | ~50-100ms |
| Memory | Shared | Separate (copy per process) |
| GIL | Limited by it | Bypasses it |
| Best for | I/O-bound | CPU-bound |
12.4 concurrent.futures
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=4) as executor:
futures = {executor.submit(fetch_url, url): url for url in urls}
for future in as_completed(futures):
url, status = future.result()
with ProcessPoolExecutor(max_workers=4) as executor: # CPU-bound
results = executor.map(is_prime, numbers)
12.5 asyncio — Cooperative Concurrency
import asyncio
async def fetch_data(url, delay):
await asyncio.sleep(delay) # Non-blocking — yields control to event loop
return f"Data from {url}"
async def main():
results = await asyncio.gather( # Concurrent — total time ≈ max(delays), not sum
fetch_data("api/users", 1),
fetch_data("api/posts", 1),
fetch_data("api/comments", 1),
)
asyncio.run(main())
await is essentially a yield to the event loop: it voluntarily releases control, letting other coroutines run while I/O is in flight. This is why a blocking call (time.sleep instead of await asyncio.sleep) inside a coroutine freezes the entire event loop — it never yields.
# TaskGroup (3.11+) — structured concurrency, cancels all on any failure
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(task_a())
task2 = tg.create_task(task_b())
# Timeout
async with asyncio.timeout(2.0):
result = await slow_operation()
12.6 Decision Matrix
I/O-bound?
├── Many connections (100+) → asyncio
├── Few connections, simple code → threading
CPU-bound?
├── Pure Python → multiprocessing
├── NumPy/Pandas → already releases GIL in C
Mixed → separate stages: asyncio/threading for I/O, multiprocessing for CPU
| Scenario | Best Choice |
|---|---|
| Web scraping 1000 URLs | asyncio + aiohttp |
| Image thumbnails (100 files) | ProcessPoolExecutor |
| API server | asyncio (or WSGI/ASGI framework) |
| ETL data pipeline | multiprocessing |
Interview Q&A — Section 12
Q1: What is the GIL and how does it affect multi-threaded Python programs?
A: The GIL is a mutex ensuring only one thread executes Python bytecode at a time, because CPython’s reference counting isn’t thread-safe without it. For CPU-bound work, threading provides no real parallelism — it can even be slower due to context-switch and lock-contention overhead. For I/O-bound work, threading works well because the GIL is released during blocking I/O calls. True CPU parallelism requires
multiprocessing(separate processes, each with its own GIL and interpreter) or C extensions/NumPy that release the GIL internally.
Q2: When would you use asyncio vs threading vs multiprocessing?
A:
asynciofor very high-concurrency I/O (thousands of simultaneous connections) with low per-task overhead, at the cost of needing an async-compatible library stack.threadingfor simpler I/O parallelism where blocking libraries are fine and concurrency needs are modest (tens to low hundreds of tasks).multiprocessingfor CPU-bound work that needs true parallelism across cores, accepting higher per-process overhead and the need for explicit inter-process communication (Queue, Pipe, shared memory).
Q3: Write a thread-safe counter and explain why the naive version fails.
counter = 0
def increment():
global counter
for _ in range(100_000):
counter += 1 # NOT atomic — read, increment, write are 3 separate steps
Without a lock, ten threads doing 100,000 increments each produce far less than 1,000,000 due to lost updates from interleaved read-modify-write cycles. Fix with
threading.Lock()wrapping the increment, making the compound operation atomic.
Q4: How does asyncio achieve concurrency on a single thread?
A: Via cooperative multitasking driven by an event loop. Each coroutine runs until it hits
await, at which point it voluntarily yields control back to the loop. The loop polls for completed I/O (viaselect/epoll/kqueue), marks the corresponding coroutines ready, and resumes them. Because there’s no preemption, a coroutine that never awaits (or calls a blocking function liketime.sleep) starves every other coroutine on that event loop.