14/34
Part 5 of 8 · Threads or processesLearn and do

The GIL lets one thread at a time run Python bytecode, and a thread that waits doesn't hold it

The reason is the GIL, the global interpreter lock: in standard CPython, only one thread at a time runs Python bytecode. Four threads doing Python arithmetic take turns. A thread that's waiting, on I/O or in time.sleep, lets the GIL go, so four sleeps overlap.

4 threads, over time
Python arithmetic, thread 1
AAAA
thread 2
BBBB
thread 3
CCCC
thread 4
DDDD
each waiting 0.1 s, thread 1
thread 2
thread 3
thread 4
running Python, holding the GILwaiting, which holds no GIL

With one GIL, threads doing arithmetic take turns. Threads that wait all wait at once.

Some C code lets go of the GIL while it works, too. The Python glossary names extension modules that release it for heavy work such as compression or hashing. Hashing is easy to try:

# four 2 MB inputs
blobs = [os.urandom(2 << 20) for _ in range(4)]


def digest(blob):
    sha = hashlib.sha256()
    for _ in range(25):
        # 50 MB of hashing per call
        sha.update(blob)
    return sha.hexdigest()

The four calls took 0.090 s in a loop and 0.023 s on 4 threads, medians of 5. Work that runs in C code like that gets the speedup on threads, with no processes needed.

All of this is the standard CPython build, the one these timings ran on. Since Python 3.13 there is also a separate free-threaded build, with the GIL disabled, where threads can run Python bytecode in parallel. Python 3.14 made it officially supported, but it's still optional. So the GIL is still there unless you choose that build.

In the editor, write thread_time(items, seconds_each, workers, holds_gil): the time a thread pool takes. Work that holds the GIL adds up, and work that waits runs in rounds of workers items.