One Lock for the Whole Interpreter

Contents
On a virtual machine with four CPUs, a Python 3.7 program counted down from forty million in 0.43 seconds with one thread. With four threads, each counting a quarter, it took 0.47. The machine had four times the hardware and the program got slightly slower, because only one thread at a time was ever allowed to run Python code. The same program hashing 64 KiB buffers with four threads ran 3.7 times faster than with one. Hashing 1 KiB buffers, it ran at the same speed as one thread. Nothing in the Python code says which of those you’ll get.
The rule behind all three is the Global Interpreter Lock: one mutex per process that a thread must hold to execute bytecode or touch any Python object. This post measures how it is passed between threads, why an I/O thread can wait ten milliseconds for a lock it needs for microseconds, how C code gets out from under it, and why the handler for a signal can’t run until a C function returns.
This is Part 6 of a series on the CPython runtime. Part 4 showed reference counts changing on every read, which is the first reason this lock exists. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.1, built from its tag with Ubuntu 18.04’s gcc 7.3.0, in a four-CPU virtual machine booting 18.04’s release kernel. The note at the end says exactly where and how.
Four threads, one at a time
import os, threading, time
def count(n):
while n:
n -= 1
N = 40000000
print("CPUs:", os.cpu_count())
for nthreads in (1, 2, 4):
threads = [threading.Thread(target=count, args=(N // nthreads,)) for _ in range(nthreads)]
wall, cpu = time.perf_counter(), time.process_time()
for t in threads:
t.start()
for t in threads:
t.join()
wall, cpu = time.perf_counter() - wall, time.process_time() - cpu
print("%d thread%s: %.2f s wall, %.2f s CPU" % (nthreads, " " if nthreads == 1 else "s", wall, cpu))
$ python3 cpu.py
CPUs: 4
1 thread : 0.43 s wall, 0.43 s CPU
2 threads: 0.44 s wall, 0.44 s CPU
4 threads: 0.47 s wall, 0.48 s CPU
The CPU time equals the wall time in every row. If four threads were running at once, the process
would use four seconds of CPU time per second of wall time. These used one. The threads are real
operating-system threads (CPython makes a POSIX thread for each threading.Thread), and the kernel
was free to put them on four CPUs. But each, before running a single bytecode instruction, has to
take the GIL, and only one can hold it. The others sleep in the kernel until it’s their turn, so
there is never more than one CPU’s worth of Python running, plus a little extra for the handing
over, which is why four threads are 10% slower than one.
Why there is one lock
Everything shared between threads in CPython is unprotected C. Every object’s ob_refcnt is
incremented and decremented with plain ++ and --, which on x86 compile to a read, an add and a
write. Two threads doing it at once can both read 1, both write 2, and lose a reference, and the
object is freed while still in use. The allocator’s free lists, the size-class pools of Part 5, the
free lists of floats and tuples, the cycle collector’s generation lists, the type attribute cache,
and every dict and list are all ordinary C data structures with no locking.
The choice was between a lock on each of those, which means an atomic instruction on every reference count change, and one lock around all of them. CPython chose one. It makes single-threaded code as fast as possible, it makes C extensions simple to write, since they can assume nothing else is touching Python objects while they run, and it gives up parallel execution of Python code.
How the lock changes hands
The GIL is implemented in Python/ceval_gil.h, and its opening comment is the best description:
/*
Notes about the implementation:
- The GIL is just a boolean variable (locked) whose access is protected
by a mutex (gil_mutex), and whose changes are signalled by a condition
variable (gil_cond). gil_mutex is taken for short periods of time,
and therefore mostly uncontended.
- In the GIL-holding thread, the main loop (PyEval_EvalFrameEx) must be
able to release the GIL on demand by another thread. A volatile boolean
variable (gil_drop_request) is used for that purpose, which is checked
at every turn of the eval loop. That variable is set after a wait of
`interval` microseconds on `gil_cond` has timed out.
...
- A thread wanting to take the GIL will first let pass a given amount of
time (`interval` microseconds) before setting gil_drop_request. This
encourages a defined switching period, but doesn't enforce it since
opcodes can take an arbitrary time to execute.
The `interval` value is available for the user to read and modify
using the Python API `sys.{get,set}switchinterval()`.
- When a thread releases the GIL and gil_drop_request is set, that thread
ensures that another GIL-awaiting thread gets scheduled.
...
*/
So the holder never gives the lock up voluntarily while it runs Python. A thread that wants it waits
on a condition variable with a timeout of interval, 5,000 microseconds by default
(DEFAULT_INTERVAL 5000). If the timeout expires and nobody has switched in the meantime, it sets
gil_drop_request, which sets the eval_breaker that Part 2 found checked at the top of the eval
loop. The holder sees it within one instruction, releases the lock, and waits until another thread
has actually taken it, which stops it from grabbing the lock straight back. This is take_gil:
while (_Py_atomic_load_relaxed(&_PyRuntime.ceval.gil.locked)) {
int timed_out = 0;
unsigned long saved_switchnum;
saved_switchnum = _PyRuntime.ceval.gil.switch_number;
COND_TIMED_WAIT(_PyRuntime.ceval.gil.cond, _PyRuntime.ceval.gil.mutex,
INTERVAL, timed_out);
/* If we timed out and no switch occurred in the meantime, it is time
to ask the GIL-holding thread to drop it. */
if (timed_out &&
_Py_atomic_load_relaxed(&_PyRuntime.ceval.gil.locked) &&
_PyRuntime.ceval.gil.switch_number == saved_switchnum) {
SET_GIL_DROP_REQUEST();
}
}
The schedule can be watched from Python. A thread can only run Python code while it holds the GIL, so if a CPU-bound thread records a timestamp every few microseconds, the gaps in its record are exactly the times it didn’t hold the lock:
# Who holds the GIL? Two CPU-bound threads each record a timestamp every 1,000 loop
# iterations. A thread can only record while it holds the GIL, so a gap in its own record
# is time it spent waiting for the other one.
import json, sys, threading, time
from array import array
def worker(log, stop):
t = time.perf_counter
while not stop:
for _ in range(1000):
pass
log.append(t())
def run(interval, seconds=0.12):
sys.setswitchinterval(interval)
logs, stop = [array("d"), array("d")], []
threads = [threading.Thread(target=worker, args=(log, stop)) for log in logs]
t0 = time.perf_counter()
for th in threads:
th.start()
time.sleep(seconds)
stop.append(1)
for th in threads:
th.join()
segments = [] # (thread, start ms, end ms)
for k, log in enumerate(logs):
start = prev = log[0]
for x in log[1:]:
if x - prev > 0.0002: # a gap longer than ten chunks: it lost the GIL
segments.append((k, (start - t0) * 1e3, (prev - t0) * 1e3))
start = x
prev = x
segments.append((k, (start - t0) * 1e3, (prev - t0) * 1e3))
segments.sort(key=lambda s: s[1])
return segments
for interval in (0.005, 0.001):
seg = run(interval)
inner = [s for s in seg if 20 < s[1] and s[2] < 100]
lengths = sorted(s[2] - s[1] for s in inner)
print("switch interval %.0f ms: %d turns between 20 and 100 ms; median turn %.2f ms" %
(interval * 1e3, len(inner), lengths[len(lengths) // 2]))
if len(sys.argv) > 1:
json.dump(seg, open(sys.argv[1] + "-%d.json" % int(interval * 1e3), "w"))
$ python3 timeline.py tl
switch interval 5 ms: 19 turns between 20 and 100 ms; median turn 5.08 ms
switch interval 1 ms: 71 turns between 20 and 100 ms; median turn 1.10 ms
The lock changed hands every 5.08 milliseconds with the default interval, and every 1.10 with
sys.setswitchinterval(0.001). Each turn is the interval, plus the time for the holder to notice
the request and the other thread to wake. The figure draws the two threads’ turns from the same
logs:
Two CPU-bound threads taking turns on the GIL
Forty milliseconds of one run, reconstructed from the threads' own timestamps. A bar is time a thread held the lock.
Hover or focus a bar for its times.
Gaps between one thread's turn and the other's are the handover: the holder noticing the drop request at its next eval-loop check, and the kernel waking the waiting thread.
The stop list deserves a word. The threads check while not stop, and the main thread appends to
it. That’s safe here because of the GIL: appending to a list is one C call, and no other thread can
see the list half-modified. Code that relies on this is relying on an implementation detail, and much
real code does.
The convoy: an I/O thread behind a CPU thread
A thread that does I/O releases the GIL around the system call. socket.recv blocks in the kernel
without holding the lock, so other threads can run meanwhile. But when the data arrives, it has to
take the GIL back to return to Python, and if a CPU-bound thread holds it, the I/O thread waits for
the full interval before even asking. Here a process sends one byte to an echo process and waits for
it to come back, first alone and then with a CPU-bound thread spinning beside it:
# Round trips through a socket to an echo process, with and without a CPU-bound thread
# in this process competing for the GIL.
import os, socket, statistics, threading, time
a, b = socket.socketpair()
if os.fork() == 0: # child process: echo forever (its own GIL)
a.close()
while True:
data = b.recv(64)
if not data:
os._exit(0)
b.sendall(data)
b.close()
def round_trips(n):
times = []
for _ in range(n):
t = time.perf_counter()
a.sendall(b"x")
a.recv(64)
times.append(time.perf_counter() - t)
return times
def spin(stop):
while not stop:
pass
alone = round_trips(1000)
stop = []
cpu = threading.Thread(target=spin, args=(stop,)); cpu.start()
busy = round_trips(200)
stop.append(1); cpu.join()
for label, t in (("alone", alone), ("with a CPU thread", busy)):
print("%-18s median %8.1f us mean %8.1f us" % (label, statistics.median(t) * 1e6, statistics.mean(t) * 1e6))
a.close()
$ python3 convoy.py
alone median 18.5 us mean 20.6 us
with a CPU thread median 10275.9 us mean 8927.4 us
A round trip that takes 18.5 microseconds alone takes 10.3 milliseconds with a busy thread in the
same process, 555 times as long, while the echo process is no slower. The round trip is two system
calls, sendall and recv, and each releases the GIL. After each, the main thread is runnable at
once but has to wait for the CPU thread’s 5 ms turn to end: two waits of one interval each, 10 ms.
(The mean is lower than the median because some calls get lucky and find the lock being handed over
anyway.)
This is the convoy effect from Beazley’s talk. Under the GIL, a thread that does many small I/O
operations runs at the speed of the CPU-bound threads’ time slices, not at the speed of its I/O.
It’s why a web server whose request threads share a process with a CPU-heavy background thread has
latencies in multiples of 5 ms. sys.setswitchinterval shrinks the waits at the price of more
switching. The structural fix, putting CPU-bound work in another process, is what the echo process
above already shows: its GIL is its own.
C code can let go
The GIL protects Python objects, so C code that doesn’t touch Python objects doesn’t need it. The C
API provides a pair of macros for that, from Include/ceval.h:
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
}
PyEval_SaveThread releases the GIL, and PyEval_RestoreThread takes it back. Between them, C code
may run in parallel with other threads, as long as it uses only its own C data. Every blocking system
call in the standard library is wrapped like this, and so are some long computations. Whether a
particular one releases the GIL is an implementation decision, and sometimes depends on the
arguments. Here is hashlib’s update, from Modules/_hashopenssl.c:
if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
self->lock = PyThread_allocate_lock();
/* fail? lock = NULL and we fail over to non-threaded code. */
}
if (self->lock != NULL) {
Py_BEGIN_ALLOW_THREADS
PyThread_acquire_lock(self->lock, 1);
EVP_hash(self, view.buf, view.len);
PyThread_release_lock(self->lock);
Py_END_ALLOW_THREADS
} else {
EVP_hash(self, view.buf, view.len);
}
with #define HASHLIB_GIL_MINSIZE 2048 in Modules/hashlib.h. Below 2,048 bytes, releasing and
retaking the lock costs more than hashing, so it hashes with the GIL held. From Python that threshold
is invisible:
import hashlib, threading, time
def work(chunks):
for c in chunks:
hashlib.sha256(c).digest()
TOTAL = 256 * 1024 * 1024
for size in (1024, 65536):
chunk = b"\x5a" * size
for nthreads in (1, 4):
per = [[chunk] * (TOTAL // size // nthreads) for _ in range(nthreads)]
threads = [threading.Thread(target=work, args=(p,)) for p in per]
t = time.perf_counter()
for th in threads:
th.start()
for th in threads:
th.join()
dt = time.perf_counter() - t
print("%5d-byte chunks, %d thread%s: %6.0f MB/s" % (size, nthreads, " " if nthreads == 1 else "s", TOTAL / dt / 1e6))
$ python3 hashing.py
1024-byte chunks, 1 thread : 2726 MB/s
1024-byte chunks, 4 threads: 2754 MB/s
65536-byte chunks, 1 thread : 4813 MB/s
65536-byte chunks, 4 threads: 17977 MB/s
The same 256 MiB, the same function. With 64 KiB chunks, four threads hash 3.7 times as fast as one: the C code ran on four CPUs at once, and only the short stretches of Python between calls took turns on the GIL. With 1 KiB chunks, four threads are no faster than one, because the hashing itself happened with the lock held. Even single-threaded, the small chunks are slower per byte, because the Python overhead of each call is paid on a fifth of a page instead of sixteen.
What four threads buy, and what one busy thread costs
Python 3.7.1 on four CPUs. Threads help only where C code releases the GIL.
Speedup of 4 threads over 1
Socket round trip, median
Hover or focus a bar for details.
Left: the dashed line is 1×, no gain. Right: bar length is the logarithm of the time, so the 555-fold difference fits; the labels give the measured medians.
This is the general rule for threads in CPython: they parallelise exactly the work that happens in C
code that releases the GIL. Network and disk I/O, compression in zlib, hashing of large buffers, and
most of NumPy’s array operations on large arrays all release it. Anything that executes Python
bytecode, or calls C code that keeps the lock, runs one thread at a time. You can’t tell from the
call which kind it is, and as hashlib shows, the same call can be either.
Signals wait for C
A Unix signal can arrive at any moment, in any thread, in the middle of anything, including
malloc, so a C signal handler may do almost nothing safely. CPython’s handler, trip_signal in
Modules/signalmodule.c, just sets a flag for the signal, sets is_tripped, and calls
_PyEval_SignalReceived, which sets the eval breaker. The Python-level handler you registered runs
later, from PyErr_CheckSignals:
int
PyErr_CheckSignals(void)
{
int i;
PyObject *f;
if (!_Py_atomic_load(&is_tripped))
return 0;
if (PyThread_get_thread_ident() != main_thread)
return 0;
...
Two consequences follow. Python signal handlers always run in the main thread, whichever thread the
kernel delivered the signal to. And they run only when the main thread’s eval loop next checks the
breaker, between bytecode instructions. A C function that runs for a long time without returning to
the eval loop, or calling PyErr_CheckSignals itself, holds the handler back for as long as it runs:
import signal, time
t0 = time.perf_counter()
def handler(signum, frame):
print(" SIGALRM handler ran at %.2f s" % (time.perf_counter() - t0))
signal.signal(signal.SIGALRM, handler)
print("alarm in 1 s; then a long call in C:")
signal.alarm(1)
total = sum(range(300000000))
print(" sum() returned at %.2f s" % (time.perf_counter() - t0))
t0 = time.perf_counter()
print("alarm in 1 s; then a long loop in Python:")
signal.alarm(1)
i = 0
while time.perf_counter() - t0 < 2.5:
i += 1
print(" loop ended at %.2f s" % (time.perf_counter() - t0))
$ python3 -u signals.py
alarm in 1 s; then a long call in C:
SIGALRM handler ran at 2.38 s
sum() returned at 2.38 s
alarm in 1 s; then a long loop in Python:
SIGALRM handler ran at 1.00 s
loop ended at 2.50 s
The alarm went off at 1 second both times. During the Python loop, the handler ran at 1.00 s, within
one instruction of the signal. During sum(range(300000000)), which iterates in C without ever
returning to the eval loop, it ran at 2.38 s, at the moment sum returned. SIGINT works the same
way, which is why Ctrl-C sometimes seems to be ignored. The default handler for it raises
KeyboardInterrupt, but only when the main thread gets back to bytecode, and any long C call that
doesn’t check for signals itself postpones that for as long as it runs.
What we covered
- CPython lets one thread at a time execute bytecode, through one lock, because reference counts, allocator state and every built-in data structure are unlocked C. Four CPU-bound threads ran no faster than one, using one CPU’s worth of time.
- Since 3.2, a waiting thread asks for the lock after
sys.getswitchinterval(), 5 ms, and the holder gives it up at its next eval-loop check. Timestamps from inside two threads showed turns of 5.08 ms, and of 1.10 ms with a 1 ms interval. - An I/O-bound thread sharing a process with a CPU-bound one waits about an interval each time it needs the lock back. A socket round trip went from 18.5 µs to 10.3 ms, the convoy effect.
- C code releases the GIL with
Py_BEGIN_ALLOW_THREADS, and only the work inside such sections runs in parallel.hashlibreleases it only for buffers of 2,048 bytes or more, so four threads hashed 3.7 times faster with 64 KiB chunks and no faster with 1 KiB ones. - Signals are noted by a C handler and handled in the main thread at the next eval-loop check, so a long C call delayed a one-second alarm to 2.38 s.
The next post leaves threads and goes back to objects, to the one type every program is full of: how CPython stores strings, and why one character can make a string four times bigger.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.1, built from the v3.7.1 tag with Ubuntu
18.04’s gcc 7.3.0, in a KVM virtual machine with 4 virtual CPUs and 4 GiB booting 18.04’s release
kernel 4.15.0-20-generic, on a minimal 18.04 userland from the release archive with OpenSSL 1.1.0g.
The kernel’s scheduler decides when a woken thread actually runs, so I used the era’s kernel for all
of this. Each script was extracted from this page and run as shown.
The numbers. Each figure is one run, with nothing else running in the VM. A rerun of every script
from the page gave the same shape: no speedup from CPU threads, median turns of 5.13 and 1.10 ms,
a busy-thread round trip of 10.2 ms against 10.7 µs alone (the idle round trip varied most between
runs), 3.6× and 1× for the hashing, and the handler held until sum returned, at 2.43 s. Absolute speeds belong to the host’s
processor. Its SHA-256 throughput is that of a recent x86 CPU with hardware SHA support, and an older
one would show smaller numbers with the same ratios.
What I worked out rather than read. The timeline is reconstructed from each thread’s own
timestamps: a gap of more than 0.2 ms (about ten loop chunks) in a thread’s record is counted as not
holding the GIL. The holder can’t record while it is being preempted by the kernel either, so a few
short gaps may be the scheduler rather than the GIL. The explanation of the 10 ms round trip as two
interval waits is inferred from its size and from take_gil, not traced inside the interpreter.
What I cited rather than ran. The C quoted here is from the v3.7.1 tag: Python/ceval_gil.h,
Include/ceval.h, Modules/_hashopenssl.c, Modules/hashlib.h and Modules/signalmodule.c. The
history (threads in 1992, Greg Stein’s 1996 patch and its slowdown, the 3.2 GIL by Antoine Pitrou,
Beazley’s 2009 and 2010 talks, bpo-7946, Larry Hastings’ Gilectomy talks from 2016) is from the
python-dev archives, the talks themselves, and the issue tracker.
What I’d still change. I measured on four virtual CPUs. On a bigger machine the GIL behaves the
same, but the cost of the handover depends on how quickly the kernel wakes the waiting thread, which
varies with hardware and load. A trace of the futex calls with perf would show the handovers directly
instead of inferring them from timestamps.
One Lock for the Whole Interpreter