Who holds the lock, who waits for it and who works without it — for three types of load, next to real measurements.
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.
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.
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