The global lock is not a separate decision but the price of the deterministic destruction from lesson 09. Here: what it actually protects, which operations are atomic, why “atomic” does not mean “correct”, and what free-threading changes.
Commit to an output and a reason before you open the answer.
import sys
print(sys.getswitchinterval())0.005Five milliseconds. What exactly happens every five milliseconds?out = []
def appender():
for i in range(50_000): out.append(i)
# four threads at once200000 elements — nothing lostA shared list, four threads, no locks. And everything is correct.cache = {}
def expensive(k):
time.sleep(0.01) # any I/O
calls.append(k)
return k * 2
def naive(k):
if k not in cache:
cache[k] = expensive(k)
return cache[k]
# eight threads call naive(7)expensive() called 8 times instead of onceThe same shared dictionary, the same safety of operations — and everything is broken.import time, threading
import numpy as np
def py_work(n=8_000_000): # every iteration needs the GIL
t = 0
for i in range(n):
t += i
return t
M = np.random.rand(1600, 1600)
def np_work(): # BLAS computes outside the interpreter
return M @ M
def compare(fn, label, repeat=3):
fn() # warm-up
def wall(k):
best = float("inf")
for _ in range(repeat):
ths = [threading.Thread(target=fn) for _ in range(k)]
t0 = time.perf_counter()
for t in ths: t.start()
for t in ths: t.join()
best = min(best, time.perf_counter() - t0)
return best
one, two = wall(1), wall(2)
print(f"{label}: one {one:.2f} s → two in threads {two:.2f} s → speed-up {2*one/two:.2f}×")
compare(py_work, "Python")
compare(np_work, "numpy ")Python: one 0.24 s → two in threads 0.48 s → speed-up 0.99×
numpy : one 0.12 s → two in threads 0.12 s → speed-up 1.98×One interpreter, the same threads, a different result.Lesson 09 showed where the GIL came from: the reference count is not atomic, and a global lock turned out to be the cheapest way to fix that. Here: how it is built and what follows from it every day.
The GIL is an ordinary mutex plus a condition variable. Any thread executing bytecode must hold it.
A thread gives up the lock by itself: when it goes into waiting, when it enters C code that has released it, or on request — when another thread has asked and the switch interval has expired.
A switch is possible only between bytecode instructions, not inside them.
Snippet A. The switch interval does not work the way it seems. A thread that wants the lock sets a request flag and waits. The holder checks the flag between instructions and, if it has been set for longer than the interval, releases the lock.
Hence an important point: until the holder reaches an instruction boundary, no request takes effect. One long operation in C that did not release the lock blocks everyone for its whole duration, however many intervals have elapsed.
Snippet B. list.append is correct without locks not by magic: it executes entirely inside one bytecode instruction, and a switch between instructions is the only possible point. The same goes for dict[k] = v, set.add, and reading and writing an attribute.
This is convenient, and it is a trap — which the next consequence leads to.
Snippet C is the main one in the lesson. Every operation here is safe: the membership check is atomic, the write to the dictionary is atomic. What is broken is the sequence: between “checked that it is not there” and “wrote it”, a thread can be preempted, and eight threads do the same expensive work eight times.
And it is precisely the call to expensive with any waiting inside that creates the window: going into I/O, a thread is guaranteed to release the lock. That is, the more “correctly” the code is written from the point of view of concurrency, the wider the race window.
lock = threading.Lock()
def cached(k):
if k not in cache: # a quick check without the lock
with lock:
if k not in cache: # a repeated check under the lock
cache[k] = expensive(k)
return cache[k]
# → expensive() called 1 time
The double check is not decoration: the first lets you not take the lock on the hot path, the second closes the window. The rule: the GIL protects the integrity of the interpreter's structures and promises nothing about your invariants.
Snippet D repeats the measurement from lesson 15, and now it is explained in full. Pure Python holds the lock all the time — two threads simply alternate. numpy releases the lock while it works in C — the threads run in parallel and give 1.9×.
Hence a working criterion that replaces the folklore “threads in Python are useless”: threads are useful exactly to the extent that your load spends time outside the interpreter — waiting, or in C code that has released the lock.
What stands in the way of removing the lock is what it appeared for: a non-atomic count in every object plus thousands of extensions counting on a monopoly. The build without the GIL (PEP 703, experimental since 3.13) solves this with three techniques.
Biased reference counting: the count is split into a local one for the creating thread and a shared one for the rest, so the typical case stays non-atomic. Immortal objects (PEP 683): for None, True and small integers the count does not move at all, removing the main points of contention. Per-object locks for containers.
The price is a different ABI and separate wheels (lesson 16), plus a slowdown of single-threaded code. And the main thing for practice: code whose correctness rested on the implicit atomicity of consequence 2 breaks there — and a lot of such code has been written.
Exactly what is atomic is an implementation detail 🔧. A list of “atomic operations” wanders around the internet, but it is about a specific bytecode compiler of a specific version. Code must not rely on it; the right answer is a lock or a queue.
The GIL is not about data safety. It does not protect your structures from logical races and does not replace transactions. It only guarantees that the interpreter itself will not fall apart.
One GIL per interpreter, not per process. Since 3.12 (PEP 684) subinterpreters can each have their own lock — parallelism within one process without threads and without shared memory. For now with limitations and little support from extensions.
Root R3: lifetime is governed by a reference count. The GIL is not an independent architectural decision but a consequence: of the three ways to make the count thread-safe (atomic operations, a lock per object, one global lock), the third was chosen as the only cheap one and the only one compatible with the extensions already written.
Chronologically this is 1992; machines are single-core, and the language was conceived as glue for C libraries. The decision was obviously right and stayed so for some fifteen years. It became a problem not because it was a mistake, but because the hardware changed.
Attempts to remove the lock were made from 1999 (a Guido project that gave a twofold slowdown of single-threaded code), and they all ran into one thing: the reference count sticks out in the public C API, and an ecosystem grew up around it. What made Python the language of numerical computing fixed the global lock in place for thirty years — and PEP 703 became possible only when a way was found not to break that ecosystem wholesale.
The exact analogy is the atomic counter in std::shared_ptr, and it is useful because it shows the fork in full. Both implementations solve one task: making reference counting safe under multithreading. C++ chose atomic operations and pays on every copy of a smart pointer in every program, including single-threaded ones. CPython chose one lock and pays with the impossibility of running bytecode in parallel.
Neither option is free, and that is worth keeping in mind when the GIL is called a shortcoming: the alternative has been carried out in a neighbouring language and has its own price, which is regularly complained about there too.
The second useful image is the big kernel lock in early SMP versions of Unix and Linux: one lock for the whole kernel, so as not to rewrite the code for multiprocessing all at once. It worked while there were few cores; it was removed over decades, one subsystem at a time. Free-threading is exactly the same story, applied to an interpreter.
Questions that come up on their own if you read closely. The answer is under the question.
Because what needed removing was not the GIL but one of the two decisions under it — and both had already grown into the ecosystem.
The GIL is not an independent decision. It stands at the intersection of two others: reference counting as the memory model (R3) and the C API as the way to extend (R6). The count is not atomic, and every C extension moves it without a lock — so a global lock is needed, otherwise the counts will drift and objects will start being freed twice.
There were attempts, and they all ran into the same thing:
Every time it came out the same: a gain for a minority that computes in Python in threads, at the expense of a majority with one thread. Guido stated the condition outright: single-threaded performance must not suffer.
PEP 703 closed the question twenty years later — but at the price of a separate build with a separate ABI, deferred freeing and biased reference counting. Not a switch, but a second version of the interpreter. That is R9 too: existing extensions cannot be broken.
Because the GIL protects the interpreter's internals, not your logic. The boundary of atomicity is a bytecode instruction, not a line of code.
x += 1 is at least four instructions: read, load the constant, add, write. Between any two of them the interpreter can hand the GIL to another thread.
A more insidious case is “check and act”, where the race shows up not as lost data but as redundant work:
import threading
cache = {}
calls = 0
def expensive(key):
global calls
calls += 1
return key * 2
def get(key):
if key not in cache: # checked
cache[key] = expensive(key) # ...and only then wrote
return cache[key]
ts = [threading.Thread(target=get, args=("k",)) for _ in range(8)]
for t in ts: t.start()
for t in ts: t.join()
print(calls) # → usually more than one
Eight threads simultaneously did not find the key and computed it eight times. The data is not corrupted — the work was simply done eight times instead of once. In production this looks like eight identical queries to the database for one cache miss.
And separately: the list of “atomic operations” wandering around the internet 🔧 — it describes the bytecode compiler of a specific version. Specialization in 3.11 has already shifted the instruction boundaries. It cannot be relied on; the right answer is always a Lock or a queue.
Not yet — unless you are hitting CPU-bound Python in threads specifically and are ready to check the whole dependency tree.
What it gives (PEP 703, the python3.13t build and later): real parallelism of pure Python code across cores. Something that did not exist for thirty years.
What it costs right now:
When to switch. When the profile shows that the time goes into Python computation, and processes do not fit because of the volume of data passed (lesson 20). In all other cases it is worth checking cheaper paths first: numpy releases the GIL and gives 1.9× on two cores already, processes work everywhere, and asyncio solves the waiting problem.
A sensible strategy for the near future is to build extensions so that they work in both builds, and to keep an eye on the matrix of wheels of your dependencies.
list.append are atomic simply because they fit into one instruction — but the atomicity of an operation does not give correctness of a scenario: between the check and the write a thread is preempted, and a naive cache calls an expensive function eight times instead of once. Threads are useful exactly to the extent that the load spends time outside the interpreter: a pure loop does not speed up at all, numpy gives 1.9× because it releases the lock. Free-threading removes the lock at the price of a different ABI and breaks code whose correctness rested on implicit atomicity.C gives no guarantees at all: shared data is protected by the programmer, and the price of a mistake is a data race with undefined behaviour. Python with its GIL is at the opposite pole: the integrity of the interpreter is guaranteed, but not of your invariants. In other words, the GIL removes a whole class of crashes (corruption of internal structures) and leaves the whole class of logical races from consequence 3.
Tellingly, C++ with its std::shared_ptr ran into the same task and chose the first of the three options: the count there is atomic. And it paid exactly what CPython was afraid of — an atomic increment costs more than an ordinary one, and everyone pays for it in single-threaded code. This is literally the alternative branch of the same decision, carried out in a neighbouring language.
Java took the third path: tracing collection instead of a count, so no global lock is needed and threads are real. The price is non-deterministic destruction and collector pauses (lesson 09).
Go made parallelism the foundation: a preemptive scheduler, goroutines across cores, and races caught by a detector in tests. And it honestly kept the same problem from consequence 3: -race exists because logical races do not go away.
Lazy initialization or memoization without a lock. It works locally; under load it does redundant work — sometimes very expensive work.
_conn = None
def get_connection():
global _conn
if _conn is None:
_conn = create_connection() # a second, goes over the network
return _conn
The classic lazy singleton. The check is atomic, the assignment is atomic — and still, when ten workers start at once, ten connections are created. Nine of them are lost afterwards, but the pool on the other side is already occupied, and the connection limit may be exhausted.
Review lets it through because the pattern looks canonical and is flawless in a single-threaded test. It shows up only on a simultaneous first access — that is, at startup under load, which makes reproducing it especially unpleasant.
import threading
_conn = None
_lock = threading.Lock()
def get_connection():
global _conn
if _conn is None: # fast path without the lock
with _lock:
if _conn is None: # close the window
_conn = create_connection()
return _conn
Checked by measurement on eight threads: the naive version triggers creation 8 times, the double-checked version — 1.
Simpler still where it applies: functools.lru_cache takes a lock around a miss itself, and a module variable initialized at the top level of the module is protected by the import lock (lesson 17). The rule: any “check, then act” sequence over shared state needs a lock, regardless of whether its parts are atomic.
Instead of arguing that “threads in Python are useless” — one check on your own load.
import time, threading
def bench(fn, arg, n=2):
t = time.perf_counter()
for _ in range(n): fn(arg)
seq = time.perf_counter() - t
th = [threading.Thread(target=fn, args=(arg,)) for _ in range(n)]
t = time.perf_counter()
for x in th: x.start()
for x in th: x.join()
par = time.perf_counter() - t
print(f"sequential {seq:.2f} s | threads {par:.2f} s | speed-up {seq/par:.2f}×")
| load | one task | two in two threads | conclusion |
|---|---|---|---|
| Python loop | 0.24 s | 0.48 s | the lock is held — threads will not help |
| numpy operation | 0.121 s | 0.125 s | the lock is released — scale with threads |
How to read the result. A speed-up close to the number of threads — the load leaves the interpreter; take ThreadPoolExecutor. No speed-up — the work is in bytecode; then, in order: the algorithm, vectorization, processes, an extension.
Why threads first and not processes straight away. Processes always give parallelism, but the data travels through pickle: a hundred-megabyte array means serialization there and back for every task. Threads share memory for free, and on numerical loads they often win precisely because of that.
The same test is worth running on a specific library: whether it releases the GIL is its author's decision, and the documentation rarely makes it clear (lesson 15).
Run the snippets and check them against your prediction. Then:
import sys
sys.setswitchinterval(1e-6)
# Run the naive cache example again. Did it get worse? And if you set 1.0?
import dis
def inc(d, k):
d[k] = d.get(k, 0) + 1
dis.dis(inc)
# How many instructions? In how many places is a switch possible?
import threading, time
def spin():
t = time.perf_counter()
while time.perf_counter() - t < 1: pass
# Start two such threads. Why is it exactly two seconds?
import sysconfig
print(sysconfig.get_config_var("Py_GIL_DISABLED"))
# False on a regular build. What changes in the answers above on free-threading?
The second question is the most telling: once you see four or five instructions per line in dis, you stop believing in the atomicity of “simple” expressions.
Python/ceval_gil.h. The whole GIL fits into one file: a structure with a mutex and a condition variable, the take and drop functions, the gil_drop_request flag and the interval logic. After consequence 1 it reads in ten minutes and removes all the mystique.
Find eval_breaker there too — the flag the interpreter checks between instructions. Not only requests to give up the lock pass through it, but also signal handling and calls of pending functions. This is literally the “instruction boundary” that consequence 1 talks about.
Lib/threading.py. The module is almost entirely Python on top of the low-level _thread. It is useful to look at Lock and RLock: you can see that the real synchronization primitive is an OS object, not something related to the GIL. Two different mechanisms that are often confused.
PEP 703. Not code, but required reading: it lists everything that had to change to remove the lock — and from that list you can see how deeply it was woven in.
From L1 you know the scheme. Here: the details that tools make visible.
The GIL is a structure with a mutex, a condition variable, a switch counter and a request flag. A thread that wants the lock waits on the condition variable with a timeout equal to the switch interval; when it expires, it sets gil_drop_request. The holder sees the flag through eval_breaker at an instruction boundary and releases the lock.
Hence two observable effects. First: a switch costs more than it seems — it means waking an OS thread, and on multicore machines two CPU-bound threads can run slower than one because of the contention over the lock. Second: the interval does not guarantee responsiveness, because it depends on how quickly the holder reaches an instruction boundary.
import sys, dis
print(sys.getswitchinterval())
# → 0.005
def inc(d, k):
d[k] = d.get(k, 0) + 1
dis.dis(inc)
# → about a dozen instructions: LOAD_FAST, LOAD_METHOD, CALL,
# BINARY_OP, STORE_SUBSCR — a switch is possible between any of them
On I/O. Standard library functions that go into a system call are wrapped in Py_BEGIN_ALLOW_THREADS (lesson 15). So a thread reading a socket does not hold the lock, and a hundred such threads work fine — the whole point of threads in Python rests on this.
What to measure when you suspect a GIL problem: py-spy dump shows where the threads are standing right now; py-spy top --gil — what share of the time is spent with the lock held. If it is close to a hundred percent with several threads, you have hit the lock specifically.
Tag v3.11.15.
Python/ceval_gil.h — the whole lock implementation: take_gil, drop_gil, the interval, the request flag.Python/ceval.c — the interpreter loop and the eval_breaker check between instructions: the very place where the switch happens.Include/internal/pycore_gil.h — the structure of the lock's state.std::shared_ptr: the same task, the other branch of the forkPython/ceval_gil.h — selectively: take_gil and drop_gil. Two hundred lines that remove the mystique.threading documentation — the write-up above is enough; go there for the synchronization primitives.