The Canon / lab 3

The GIL over time

Who holds the lock, who waits for it and who works without it — for three types of load, next to real measurements.

CPython 3.11.15Linux x86-64, 2 coresfor chapters 19 and 20

Hundreds of articles have been written about the GIL, and most of them repeat one mistake: they assume the GIL makes threads useless. It makes exactly one scenario useless — pure Python bound by the processor. Below you can see how the three cases differ: the diagram is a model of the behaviour, the numbers next to it are real measurements on this machine.

load
threads
switch interval
0 ms
holds the GIL waits for the GIL computes in C, GIL released sleeps on I/O

1The second effect: the switch interval is a delay

The first diagram shows throughput. There is an effect it does not show, and in production it hurts more: a thread waiting for a network response will not get control before the busy thread's switch interval expires. One CPU-bound thread in the process, and the latency of the whole web service is tied to that number.

The measurement: one thread spins an empty loop, the second does time.sleep(0.001) and measures how late it woke up. Everything here is real, with no model.

sys.setswitchinterval

2Check it by hand

import sys, time, threading, statistics

sys.setswitchinterval(0.005)          # the default value

ev = threading.Event()
lat = []

def burner():                          # one thread occupies the GIL
    x = 0
    while not ev.is_set():
        x += 1

def responder():                       # the other tries to wake up quickly
    for _ in range(80):
        t0 = time.perf_counter()
        time.sleep(0.001)
        lat.append((time.perf_counter() - t0 - 0.001) * 1000)

b = threading.Thread(target=burner, daemon=True); b.start()
r = threading.Thread(target=responder); r.start(); r.join()
ev.set()

print("median delay, ms: %.2f" % statistics.median(lat))
# → about 5 ms: exactly the switch interval
# without the burner thread the same measurement gives 0.09 ms

3What follows from this

The diagram is a model: it faithfully reproduces the rule “one thread holds the GIL, preemption by interval”, but it is not a trace of a real scheduler. The numbers next to it and the whole second block are real measurements on CPython 3.11.15, Linux x86-64, 2 cores. Telling these two statuses apart is the same habit as telling 🔒 from 🔧.

Written by · The Python Canon