What is the GIL
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode at once in CPython.
Why it exists
CPython's memory management is not thread-safe. The GIL simplifies reference counting by ensuring only one thread mutates Python objects at a time.
When it matters
- CPU-bound multithreading: threads won't speed up compute-heavy work
- I/O-bound work: threads still help — they release the GIL while waiting on I/O
import threading
import requests
def fetch(url: str) -> None:
resp = requests.get(url, timeout=10)
print(url, resp.status_code)
urls = ["https://example.com"] * 10
threads = [threading.Thread(target=fetch, args=(u,)) for u in urls]
for t in threads:
t.start()
for t in threads:
t.join()
Practical takeaway
Use multiprocessing or asyncio for CPU-bound and I/O-bound workloads respectively — don't assume threads always parallelize Python code.