Lesson 38 of 52Concurrency and performance
Threads and the GIL
What the GIL really guarantees, why threads still speed up I/O, and how to avoid races and deadlocks with locks, queues and thread pools.
A nightly job calls a partner API once for each of 2,000 shops, using the blocking requests library. Each call takes about a second, so the job runs for over half an hour. You wrap the loop in a thread pool with 20 workers and it finishes in under two minutes. A week later the finance team asks why the "shops processed" total is a few hundred short. Threads gave you the speed-up and a race condition in the same change. This lesson is about getting the first without the second: what the GIL does and does not protect, which tools to reach for, and how to debug a program that has frozen. You met the GIL in one paragraph in The Story of Python and saw single-threaded concurrency in Async and Await; this is the full picture.
Five ways to do more than one thing
Python gives you several models of concurrency. You met asyncio in Async and Await. Here is the full map, so you can see where threads fit.
| Model | Parallel Python code? | Cost per unit | Best for |
|---|---|---|---|
asyncio | No, one thread | Tiny (thousands of tasks) | Many network waits, with async libraries |
| Threads | No in the default build (GIL) | About an OS thread each | Blocking I/O, sync libraries, C code that releases the GIL |
| Processes | Yes | A whole interpreter plus pickling | CPU-bound pure Python |
| Subinterpreters (3.14) | Yes, one GIL each | Less than a process | CPU-bound work with simple, shareable inputs |
| Free-threaded build | Yes, with threads | Some single-thread slowdown | CPU-bound threads, if your libraries support it |
The rule of thumb that still holds: waiting means asyncio or threads, computing means processes (or native code). The next lesson, Processes, Subinterpreters and Free-Threaded Python, covers the bottom three rows. This one is about threads.
Pick threads over asyncio when the code you must call is synchronous: requests, boto3, a sync database driver, an SDK that has no async version. Rewriting all of that to async is a big job. A thread pool around the existing calls is ten lines.
What the GIL actually guarantees
CPython's Global Interpreter Lock is a single lock per interpreter. A thread must hold it to run Python bytecode. So in the default build, at any instant, only one thread in the process is executing Python code, even on an 18-core laptop.
That is a narrower guarantee than people think. The GIL is passed between threads in two ways:
- Voluntarily, around blocking calls.
socket.recv,time.sleep, file reads,select: CPython releases the GIL before the system call and takes it back after. While one thread waits on the network, another runs Python. - Forcibly, on a timer. If a thread holds the GIL for longer than the switch interval (
sys.getswitchinterval(), 5 ms by default), the waiting thread asks for it and the running thread hands it over at its next safe point.
Many C extensions also release the GIL while they crunch numbers in C: hashlib on large inputs, zlib, most of NumPy, image libraries. Threads give real parallel speed-ups for that work.
A holds the GIL and runs Python code. B is ready, but has to wait for the lock.
Here is the effect measured. Four tasks each run either a pure-Python prime count or a SHA-256 hash of a 100 MB buffer, first on one thread and then on four. This ran on CPython 3.14 (default build):
import hashlib
import os
import time
from concurrent.futures import ThreadPoolExecutor
def count_primes(limit: int) -> int:
count = 0
for n in range(2, limit):
if all(n % d for d in range(2, int(n ** 0.5) + 1)):
count += 1
return count
BLOB = os.urandom(100_000_000) # 100 MB, made once
def hash_blob(_: int) -> str:
return hashlib.sha256(BLOB).hexdigest()
def timed(label, fn, args, workers):
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=workers) as pool:
list(pool.map(fn, args))
print(f"{label:<28} {time.perf_counter() - start:5.2f}s")
timed("pure Python, 1 thread", count_primes, [200_000] * 4, 1)
timed("pure Python, 4 threads", count_primes, [200_000] * 4, 4)
timed("hashlib, 1 thread", hash_blob, range(4), 1)
timed("hashlib, 4 threads", hash_blob, range(4), 4)pure Python, 1 thread 0.56s
pure Python, 4 threads 0.56s
hashlib, 1 thread 0.12s
hashlib, 4 threads 0.03sFour threads of pure Python: no gain at all. Four threads of hashing: four times faster, because hashlib drops the GIL while it hashes. "Threads do not help CPU work" is only true for CPU work done in Python bytecode.
requests, then compresses it with zlib. Which statement is closest to the truth on the default CPython build?Race conditions still happen with a GIL
The GIL protects CPython's own internals, such as reference counts and the inside of a dict. It does not make your sequence of steps atomic. A thread switch can land between any two bytecodes, and counter += 1 is several:
Press Run (⌘ Enter) to see what happens.Load the value, add one, store it back. If thread A loads 0, a switch happens, thread B loads 0 and stores 1, then A stores 1, one increment is gone. This is a lost update. Real threads cannot run in this browser, so here is the same thing with generators: each yield is a point where the scheduler may switch, exactly as the operating system may.
Press Run (⌘ Enter) to see what happens.Now with real threads. This script does the same read, pause, write, where the pause is time.sleep(0). In real code the pause is a log call, a database read, anything that lets another thread in.
import threading
import time
balance = 0
lock = threading.Lock()
def deposit_unsafe(times):
global balance
for _ in range(times):
current = balance # read
time.sleep(0) # any pause: I/O, a log call, a slow function
balance = current + 1 # write
def deposit_safe(times):
global balance
for _ in range(times):
with lock:
current = balance
time.sleep(0)
balance = current + 1
for fn in (deposit_unsafe, deposit_safe):
balance = 0
threads = [threading.Thread(target=fn, args=(1_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{fn.__name__}: expected 4000, got {balance}")deposit_unsafe: expected 4000, got 1000
deposit_safe: expected 4000, got 4000Three quarters of the deposits vanished. A subtler point: if you delete the sleep and run a bare counter += 1 loop on 3.14 with the GIL, you will probably get the right answer every time. Recent CPython only checks for a thread switch at certain points, such as the jump back to the top of a loop, so this tiny loop happens to survive. The same script on the free-threaded 3.14 build printed got 1141645 out of 4,000,000. Code that is "correct" only because of where the interpreter happens to switch is a bug waiting for a new Python version.
The other classic race is check-then-act: if key not in cache: cache[key] = load(key). Two threads both see the key missing and both run the expensive load. Or if account.balance >= amount: account.balance -= amount, and two withdrawals both pass the check. The fix is the same: the check and the action must happen under one lock.
What does this print?
shared = {"n": 0}
def worker(times):
for _ in range(times):
current = shared["n"]
yield
shared["n"] = current + 1
threads = [worker(2), worker(2), worker(2)]
while threads:
for t in list(threads):
try:
next(t)
except StopIteration:
threads.remove(t)
print(shared["n"])The threading toolkit
The threading module has a small set of tools. You need all of them at some point, and most often just two: Lock and queue.Queue.
import threading
t = threading.Thread(target=download, args=(url,), name="downloader-1")
t.start() # begins running download(url) on a new OS thread
t.join(timeout=30) # wait for it to finish (or give up after 30 s)Lock: mutual exclusion. Always use it aswith lock:so it is released even when the block raises. Keep the locked section short: no network calls inside it.RLock: a re-entrant lock. The same thread can acquire it again without blocking itself. Useful when a locked method calls another locked method. It can also hide a design where locking is spread too widely.Event: a flag threads can wait on.stop = threading.Event(), workers loopwhile not stop.is_set(), andstop.wait(5)doubles as an interruptible sleep. This is the clean way to shut workers down.Condition: "wait until some state is true", with a lock attached. It is the building block underqueue.Queue. You rarely need it directly.Semaphore(n): at mostnthreads inside a section at once. Use it to cap connections to a fragile partner API.- Daemon threads (
daemon=True) are killed abruptly when the main thread exits. Nofinallyblocks run, files may be half-written. Use them only for work that is safe to lose, such as a metrics heartbeat. Prefer anEventand ajoin.
Match each need to the threading tool.
Prefer queues to shared state
Most thread bugs come from many threads touching the same mutable object. The way out is to stop sharing: give each piece of data one owner, and pass work between threads through a queue.Queue. The queue does its own locking, and get() blocks until there is something to take.
import queue
import threading
import time
jobs: queue.Queue[str | None] = queue.Queue(maxsize=10) # bounded: back-pressure
results: queue.Queue[str] = queue.Queue()
def downloader(worker_id: int) -> None:
while True:
url = jobs.get()
if url is None: # sentinel: no more work
jobs.task_done()
return
time.sleep(0.2) # stands in for the blocking download
results.put(f"worker {worker_id} saved {url}")
jobs.task_done()
workers = [threading.Thread(target=downloader, args=(i,)) for i in range(3)]
for w in workers:
w.start()
for n in range(6):
jobs.put(f"/reports/{n}.csv") # blocks if the queue is full
for _ in workers:
jobs.put(None) # one sentinel per worker
jobs.join() # wait until every item is task_done()
for w in workers:
w.join()
while not results.empty():
print(results.get())worker 0 saved /reports/0.csv
worker 2 saved /reports/1.csv
worker 1 saved /reports/2.csv
worker 2 saved /reports/4.csv
worker 0 saved /reports/3.csv
worker 1 saved /reports/5.csvNotice the order is not the input order. Which worker finishes first depends on timing. Two details carry over to every queue design you will meet, including Celery and Kafka. A bounded queue (maxsize) gives back-pressure: a fast producer blocks instead of filling memory. A sentinel, one per worker, tells consumers to stop.
ThreadPoolExecutor: the tool you will use most
At work you rarely create Thread objects by hand. concurrent.futures.ThreadPoolExecutor keeps a pool of worker threads and gives you a Future for each job: a handle to a result that is not ready yet.
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(order_id: int) -> str:
time.sleep(0.5) # stands in for a blocking HTTP call
if order_id == 3:
raise ValueError(f"order {order_id} not found")
return f"order {order_id}: ok"
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=8) as pool:
futures = {pool.submit(fetch, i): i for i in range(1, 9)}
for fut in as_completed(futures):
try:
print(fut.result())
except ValueError as exc:
print("failed:", exc)
print(f"8 calls took {time.perf_counter() - start:.2f}s")order 1: ok
failed: order 3 not found
order 7: ok
order 6: ok
order 2: ok
order 5: ok
order 8: ok
order 4: ok
8 calls took 0.51sEight half-second calls in half a second. What to know about the API:
submit(fn, *args)returns aFutureat once.fut.result(timeout=...)blocks until it is done and returns the value, or re-raises the exception from the worker. If you never callresult(), a failure disappears silently. This is the most common thread-pool bug in code review.as_completed(futures)yields futures as they finish, fastest first. Good for progress bars and for handling failures as they come.pool.map(fn, items)returns results in input order, and raises the first exception when you reach that item. Simpler, but one slow item holds back everything after it.wait(futures, return_when=FIRST_EXCEPTION)returns(done, not_done)sets, for "stop at the first failure" logic.withshuts the pool down and waits for running jobs.pool.shutdown(cancel_futures=True)drops jobs that have not started.- The default
max_workersismin(32, cpu_count + 4). For I/O work, size it to what the other side can take, not to your cores. Twenty threads hammering a partner API with a limit of five requests per second just gets you rate-limited.
From async code, await asyncio.to_thread(fn, arg) runs a blocking call on the event loop's default thread pool. Asyncio in Depth covers this in "Mixing sync and async".
threading.local and contextvars
Sometimes each thread needs its own copy of something: a database connection that is not thread-safe, or the current request id for logging. threading.local() gives each thread its own attributes. contextvars.ContextVar gives each context its own value. Asyncio creates a new context for each task, which is why logging and tracing libraries use contextvars.
Thread pools reuse threads, and that is where per-thread state leaks. Here one worker thread handles two requests, and the second has no logged-in user:
import contextvars
import threading
from concurrent.futures import ThreadPoolExecutor
local = threading.local()
user = contextvars.ContextVar("user", default="anonymous")
def handle(name: str | None) -> str:
seen = f"local={getattr(local, 'user', 'anonymous')} ctx={user.get()}"
if name:
local.user = name
user.set(name)
return seen
with ThreadPoolExecutor(max_workers=1) as pool: # one reused worker thread
for name in ("alice", None): # None: a request with no login
ctx = contextvars.copy_context() # fresh copy per task
print(pool.submit(ctx.run, handle, name).result())local=anonymous ctx=anonymous
local=alice ctx=anonymousThe threading.local value from Alice's request is still on the thread when the anonymous request arrives. That is a security bug. The context variable is clean because each task ran in its own copied context. Without the copy_context() line, a plain submit would leak the context variable too, because a pool does not create fresh contexts for you. Use contextvars, and run each unit of work in its own context.
Deadlocks and how to find them
A deadlock is two threads each holding a lock the other needs. Neither can move, the CPU sits at zero, and the process looks alive but does nothing.
transfer takes the accounts lock first.
The standard fix is a global lock order: every code path that needs both locks takes accounts_lock first, then audit_lock. Other defences are holding one lock at a time, lock.acquire(timeout=5) so a stuck thread fails loudly, and, best of all, a queue design with no shared locks.
To diagnose a frozen process you need every thread's stack. On a live process, py-spy dump --pid 1234 prints them without stopping it. Inside your own code, the standard library's faulthandler can dump them on a timer:
import faulthandler
import threading
import time
faulthandler.dump_traceback_later(2, exit=True) # dump all stacks after 2 s, then exit
accounts_lock = threading.Lock()
audit_lock = threading.Lock()
def transfer():
with accounts_lock:
time.sleep(0.1)
with audit_lock:
pass
def report():
with audit_lock:
time.sleep(0.1)
with accounts_lock:
pass
a = threading.Thread(target=transfer, name="transfer")
b = threading.Thread(target=report, name="report")
a.start(); b.start()
a.join(); b.join()Timeout (0:00:02)!
Thread 0x0000000170ce3000 [report] (most recent call first):
File "deadlock.py", line 19 in report
...
Thread 0x000000016fcd7000 [transfer] (most recent call first):
File "deadlock.py", line 13 in transfer
...
Thread 0x00000001fbc3a1c0 (most recent call first):
File ".../threading.py", line 1133 in join
File "deadlock.py", line 25 in <module>Each thread is stuck on the line that takes its second lock. Thread names appear in the dump on recent versions, which is one more reason to name your threads. In a long-running service, faulthandler.register(signal.SIGUSR1) lets you trigger the same dump with kill -USR1 <pid> on Linux or macOS.
Put these steps of a clean thread-pool shutdown in order.
- Tap the steps below in the right order.
- GIL
- CPython's global interpreter lock: a thread must hold it to run Python bytecode, so one thread runs Python at a time in the default build.
- race condition
- A bug where the result depends on the timing of threads, such as two threads reading the same value before either writes.
- lost update
- A race where one thread's write overwrites another's, so an increment or change silently disappears.
- critical section
- A block of code that must not run in two threads at once; guard it with a Lock.
- Future
- A handle to the result of work submitted to an executor; result() returns the value or re-raises the worker's exception.
- deadlock
- Two or more threads each waiting for a lock another one holds, so none can continue.
- context variable
- A contextvars.ContextVar: a value scoped to the current context, copied for each asyncio task.