Threads, Processes & GIL
Python's GIL (Global Interpreter Lock) means threads can't run Python bytecode in parallel — use multiprocessing or concurrent.futures for CPU-bound work.
Introduction
Python's GIL (Global Interpreter Lock) means threads can't run Python bytecode in parallel — use multiprocessing or concurrent.futures for CPU-bound work.
Understanding the topic
Core concepts to understand:
- GIL = one Python instruction at a time per process.
- Threads good for I/O, bad for CPU.
multiprocessingbypasses the GIL.concurrent.futuresis the high-level API.
Syntax reference
Visual flow / code:
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor# I/O-bound: threadswith ThreadPoolExecutor(max_workers=8) as pool:results = list(pool.map(fetch_url, urls))# CPU-bound: processeswith ProcessPoolExecutor() as pool:results = list(pool.map(heavy_compute, data))
Execution workflow
GIL = one Python instruction…
GIL = one Python instruction at a time per process.
Real-world use
Python 3.13 introduces an experimental no-GIL build (PEP 703). For now: threads for I/O, processes for CPU, async for thousands of connections.
Best practices
- Threads for I/O.
- Processes for CPU.
- Async for very-high-fanout I/O.
Common mistakes
- Trying to speed up NumPy with threads — usually works (releases GIL), but pure Python doesn't.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionWhat is the GIL?+
Answer
Follow-up
x += 1 thread-safe?2IntermediateQuestionThreads vs processes vs async — when?+
Answer
asyncio for large numbers of concurrent network I/O operations when libraries support it. Use threads for blocking I/O when you cannot use async, or for libraries that release the GIL. Use processes (multiprocessing or ProcessPoolExecutor) for CPU-bound pure-Python work. Measure first, because the right choice depends on the bottleneck and on how much data must be passed around.Follow-up
3AdvancedQuestionWill Python remove the GIL?+
Answer
Follow-up
Summary
In summary: GIL serializes Python bytecode. Pick the right tool for the workload.