01C.5 The Global Interpreter Lock (GIL)

FoundationsLesson 5 of 714,441 words11 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

Every Python engineer eventually hears two sentences that seem to contradict each other: "threads make Python programs faster" and "Python threads cannot use more than one core". Both are true, and the thing that reconciles them is a single lock inside the reference implementation of Python: the Global Interpreter Lock, or GIL. This lesson explains what it is, why it was built, exactly how a thread gets it and gives it up, and what it does and does not protect. Then we measure it: CPU-bound threads that do not scale, I/O-bound threads that do, a native call that freezes every other thread, and a "convoy effect" that makes a socket ping-pong thousands of times slower. After that we look at the way out: processes, native libraries that release the lock, subinterpreters with their own lock (new in the standard library in Python 3.14), and free-threaded CPython, the build with no GIL at all, which became officially supported in 3.14. We end with a decision table for AI workloads (tokenizing, embedding, PDF parsing, JSON, regex), a measuring toolkit, and a gallery of myths. Everything runs on the standard library alone: no API key, no packages, no network.

What you'll learn

  • What the GIL is, in one sentence and in one analogy, and the one design decision (reference counting) that made it necessary
  • A short history: why threads came first, why the lock stayed, Larry Hastings' Gilectomy, and the 3.2 rewrite that introduced the switch interval
  • How it works: the eval breaker, sys.getswitchinterval(), forced hand-off, release around blocking calls and around long native calls (Py_BEGIN_ALLOW_THREADS)
  • Four measured demonstrations: CPU-bound threads versus processes, I/O-bound threads, one long C call that stalls everything, and the convoy effect
  • What the GIL protects (the interpreter's own consistency) and what it does not (your logic); the link to 01C.3
  • The escape hatches, compared: processes, native code, subinterpreters (PEP 684, PEP 734), free-threaded CPython (PEP 703, PEP 779)
  • How to check which build you run, how to force the GIL on or off, and how to tell whether a package supports free threading
  • How to measure whether the GIL is your bottleneck, and a reusable scaling harness
  • A decision table for AI workloads, and a gallery of myths and failures

What you don't need

  • The definitions of concurrency, parallelism, CPU-bound and I/O-bound, and context switching: 01C.1 owns them (the GIL's time slice is the interpreter-level cousin of the OS time slice in its 5.5).
  • Race conditions in depth: 01C.3 owns them; here we only draw the line between "what the GIL guarantees" and "what you must lock".
  • Shared memory and the IPC menu: 01C.7.
  • C, Rust or Cython knowledge. Native code appears only as a picture of what happens inside a library.
  • An API key, a provider SDK, or any installed package.

Setup

You need Python 3.11 or newer (3.13 or 3.14 recommended; the subinterpreter examples in Part 6 need 3.14). Check your version:

bash
python3 --version
powershell
py --version

Save each snippet as a .py file and run it with python3 file.py (Windows: py file.py). No API key needed. Every Output: block came from Python 3.14.6 on macOS, a normal build with the GIL enabled, on a machine with 10 cores. A free-threaded build was not installed here (and the lesson's rules forbid installing one), so everything said about running without the GIL comes from the official documentation and PEPs and is labelled as such. Timings and thread-scheduling results depend on your machine: those blocks are labelled Example output (illustrative — your exact output will differ): and the text says which relationship, not which number, to look for.


What you must be able to do after this lesson#

  • Explain what the GIL is and why CPython has it
  • Explain why threads do not speed up CPU-bound Python code but do help I/O-bound code
  • Measure whether the GIL is the bottleneck with a scaling test
  • Explain what the GIL does and does not protect
  • Choose between processes, native code, subinterpreters and free-threaded CPython
  • Check which Python build you are running

Why this matters for an AI engineer#

An AI service does two very different kinds of work at once. Most of the time it waits (for the model, the vector database, the tool). Some of the time it computes in Python (parse a PDF, split text, count tokens, clean JSON, post-process embeddings). The GIL decides which of those two kinds of work threads can speed up. Misreading it produces the two classic production mistakes: adding threads to CPU-heavy code and getting nothing, or adding processes to waiting code and paying for memory you did not need. You will hear:

You'll hear... You'll understand it after...
"Python can't do real threading because of the GIL" Part 3 and Part 4
"Threads are fine for LLM calls, useless for parsing" 3.2 and 3.1
"NumPy releases the GIL" 2.4 and 9.1
"Why does my server stutter when one request does a big sorted()?" 3.3
"Python 3.14 has no GIL now?" Part 7
"Subinterpreters give you a GIL per interpreter" Part 6
"Use ProcessPoolExecutor for CPU work" Part 5
"Which of my dependencies support free threading?" 7.5

Part 1: What the GIL is, and why it exists#

1.1 One lock, one thread at a time#

The Global Interpreter Lock is a mutex (a lock that one thread holds at a time) inside the standard CPython interpreter. Python's own C-API documentation puts it plainly: unless you are on a free-threaded build, "the Python interpreter is generally not thread-safe", so "there's a global lock, called the global interpreter lock or GIL, that must be held by a thread before accessing Python objects", and "only a thread that holds the GIL may operate on Python objects or invoke Python's C API".

In one sentence: in a normal CPython process, only one thread at a time executes Python bytecode, however many cores you have. Threads still exist, are real operating-system threads, and the OS can run them on different cores; but to run Python code each thread must first hold the lock, and there is only one lock.

An analogy: a kitchen with ten cooks (cores) and one recipe book (the interpreter). Cooks may only touch the book while holding the single "book token". A cook who is waiting for the oven (a network reply, a disk read) hands the token back, so someone else can read the book. A cook who is chopping from memory without looking at the book (a native library) can also hand it back. But a cook who keeps flipping pages (pure Python code) keeps the token, and the other nine stand idle. Ten cooks do not make a recipe-reading job ten times faster when only one may read at a time.

1.2 Why it exists: reference counting#

Every CPython object carries a reference count: a small integer saying how many references to the object exist. When it reaches zero the object is freed at once. This is CPython's main memory-management mechanism (01C.6 owns the details). You can watch it:

python
# e01_refcount.py: every Python object carries a reference count; the GIL is what keeps it honest.
import sys

ticket = ["refund request", "order #1042"]       # a fresh list: one name points at it
print("names pointing at ticket:", sys.getrefcount(ticket) - 1)   # -1: the call's own argument

queue = [ticket]                                  # a second reference (inside another list)
alias = ticket                                    # a third
print("after queue + alias:", sys.getrefcount(ticket) - 1)

del alias, queue
print("after del:", sys.getrefcount(ticket) - 1)

# Immortal objects (3.12+): None never changes its count, so no one needs to protect it.
before = sys.getrefcount(None)
holders = [None] * 1000
print("None count unchanged after 1000 new references:", sys.getrefcount(None) == before)
Output · Python 3.14.64 lines
names pointing at ticket: 1
after queue + alias: 3
after del: 1
None count unchanged after 1000 new references: True

Now the problem. Reading, copying and passing a reference around changes that integer constantly: x = ticket increments it, a name going out of scope decrements it. In machine terms an increment is load, add one, store, which is exactly the lost-update shape from 01C.3 §2.1. If two threads increment the same count at once without protection, one increment is lost, the count ends too low, and eventually the object is freed while something still points at it: a crash, or worse, silent memory corruption.

There are two ways to make that safe. One is a lock on every object (or atomic instructions on every count), which is slow and complex and makes every single-threaded program pay for something it does not need. The other is one lock for the whole interpreter: if only one thread runs Python code at a time, no count is ever updated by two threads at once, and no per-object locking is needed at all. CPython chose the second. That is the GIL.

It bought three things:

Benefit Why it mattered
Safe reference counting with plain, non-atomic increments Fast: single-threaded code pays almost nothing for the possibility of threads
Memory safety of built-in types (list, dict, set) without a lock inside each A list.append cannot corrupt the list's internal array (Part 4)
Easy C extensions: native code called from Python can assume it is the only thread touching Python objects A huge ecosystem (NumPy, database drivers, image libraries) was written in that style, with no thread-safety code at all

The third point is why removing the GIL is so hard: it is not only the interpreter that relies on it, it is every C extension ever written.

1.3 A short history#

The milestones that matter for this lesson, from the official documents:

When What Source
Python 3.2 (2011) The GIL was re-implemented to switch threads on a time interval (sys.setswitchinterval, default 5 ms) instead of every N bytecodes (the old design counted "ticks" and, on multi-core machines, could make threads fight over the lock) sys docs: "Added in version 3.2"
Python 3.12 (2023) PEP 684: each subinterpreter can have its own GIL (C API only); PEP 683 immortal objects made it possible PEP 684: Final, 3.12
Python 3.13 (2024) PEP 703: an optional, experimental free-threaded build with no GIL; sys._is_gil_enabled() added sys docs: "Added in version 3.13"
Python 3.14 (2025) PEP 779: free-threaded Python officially supported (still optional, not the default); PEP 734: concurrent.interpreters and InterpreterPoolExecutor in the standard library PEP 779: Final; PEP 734: Final
Python 3.15 (released 9 October 2026) free-threading keeps maturing: a stable ABI for free-threaded builds (PEP 803, abi3t), and the official macOS binaries now install free-threading support by default. The GIL build is still the default What's New in 3.15

(As of November 2026. Sources are listed in the report, and at the end of this lesson.)

1.4 What the GIL is not#

It is not... Because...
A lock on your data It protects the interpreter's internals. Your counter += 1 is still a race (01C.3 §2.4)
Held for the whole program run It is released during blocking I/O, time.sleep, lock waits, and long native calls (Part 2)
The reason Python is "slow" Single-threaded Python speed is set by the interpreter loop, not by the GIL. The GIL only limits how many cores one process's Python code can use
A limit on asyncio A single-threaded event loop is already one-at-a-time by design (01C.2); the GIL costs it nothing
Going away "in 3.14" 3.14 made the opt-in free-threaded build official. The default build you get from brew, apt or python.org still has the GIL (Part 7)

What this means for an AI engineer: the GIL is a fact about one resource: the right to run Python bytecode. Work that waits, or runs inside native code that lets go of the lock, scales with threads. Work that runs Python bytecode does not. Every decision in the rest of the lesson is about which kind you have.


Part 2: How the GIL works#

Deep-dive

2.1 The eval loop and the eval breaker#

CPython runs your code in a big loop that fetches one bytecode instruction after another (LOAD_FAST, BINARY_OP, CALL...). A thread holding the GIL stays in that loop. To let another thread in, the running thread must notice it should stop. It cannot be interrupted at a random machine instruction (the interpreter's data structures would be half-updated), so CPython uses a polite mechanism, a flag the loop checks at safe points. In the C source this flag is part of the eval breaker: at certain instructions (backward jumps and function calls, in recent versions) the loop checks it, and if a request is pending, it handles it before continuing. A request to drop the GIL is one of the things that can be pending.

This is why the FAQ says: "In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via sys.setswitchinterval()." It is also why one bytecode instruction, including all the C code it calls, runs without another Python thread in the middle. That, and nothing more, is the "atomicity" the GIL gives you.

2.2 The switch interval and the forced hand-off#

Here is the algorithm for two threads, A running Python code and B wanting to:

  1. Thread B asks for the GIL and finds it taken. It waits on a condition variable with a timeout equal to the switch interval (default 5 milliseconds, sys.getswitchinterval()).
  2. If A releases the GIL during that time (because A blocked on I/O, say), B gets it at once.
  3. If the timeout expires and the GIL is still held by the same thread, B sets a drop request flag (gil_drop_request in the C source).
  4. A sees the request at its next eval-breaker check, releases the GIL, and, here is the "forced hand-off", waits until another thread has actually taken it, so that A cannot immediately re-grab the lock before B wakes.
  5. B runs. When it blocks, finishes, or in turn gets a drop request, the cycle repeats.
sequenceDiagram
    participant A as Thread A (CPU loop)
    participant G as The GIL
    participant B as Thread B (waiting)
    A->>G: holds the lock, runs bytecode
    B->>G: wants it, waits up to the switch interval (5 ms)
    Note over B,G: timeout expires: B sets gil_drop_request
    A->>A: at the next eval-breaker check, sees the request
    A->>G: releases the lock
    G->>B: B acquires it (A is made to wait until B has it)
    B->>B: runs bytecode
    B->>G: blocks on a socket read: releases the lock
    G->>A: A takes it back

The documentation is careful about what this does and does not promise. For sys.setswitchinterval: "This floating-point value determines the ideal duration of the 'timeslices' allocated to concurrently running Python threads. Please note that the actual value can be higher, especially if long-running internal functions or methods are used. Also, which thread becomes scheduled at the end of the interval is the operating system's decision. The interpreter doesn't have its own scheduler."

Three consequences follow from that paragraph, and we will measure each in Part 3:

  • The slice is a request, not a deadline. If the running thread is inside one long native call, it cannot see the drop request until the call returns.
  • Fairness is the OS's business. Python does not queue waiting threads; with several waiters, which one wakes is up to the operating system's scheduler.
  • A smaller interval means lower latency for waiting threads and more switching. A larger interval means the opposite.
  • Signals wait too. Python-level signal handlers (and so KeyboardInterrupt) run only in the main thread, between bytecodes. A long GIL-holding native call in the main thread therefore delays Ctrl-C and SIGTERM handling until it returns, which matters for graceful shutdown of services.

2.3 Releasing the lock around blocking calls#

The most important rule in the whole lesson: a thread that is about to wait does not need the GIL, so it lets go of it. Every blocking call in the standard library does this: time.sleep, socket.recv, file.read, subprocess waits, threading.Lock.acquire, queue.Queue.get, select. While thread A sleeps in the kernel, thread B runs Python code on its behalf.

That is the entire reason threads help I/O-bound programs. When the wait ends, thread A asks for the GIL back and waits its turn (up to one switch interval; this is where the convoy effect in 3.4 comes from).

2.4 Releasing the lock in native code#

The same trick is available to native extensions. The C API documentation describes a pair of macros, Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS: the first "expands to { PyThreadState *_save; _save = PyEval_SaveThread();" (it releases the GIL by detaching the thread's state) and the second "expands to PyEval_RestoreThread(_save); }" (it takes the GIL back). The docs note that this is used for blocking I/O, but also for long-running native code, naming the standard zlib and hashlib modules as examples that "detach while compressing or hashing". Between the macros, the code must not touch any Python object.

flowchart LR
    A["Python code calls hashlib.sha256(big_bytes)"] --> B["C code copies a pointer to the bytes"]
    B --> C["Py_BEGIN_ALLOW_THREADS: GIL released"]
    C --> D["Hash 19 MB in native code: other Python threads run, on other cores"]
    D --> E["Py_END_ALLOW_THREADS: wait to take the GIL back"]
    E --> F["Return a Python object"]

What the documentation says, verified, about what releases the GIL in the standard library:

Library What the docs say
hashlib "the Python GIL is released while computing a hash supplied more than 2047 bytes of data at once in its constructor or .update method"
zlib The CPython FAQ names it as a module that releases the GIL; the zlib page itself says nothing about it (we measure it below)
NumPy "Many NumPy operations release the GIL, so unlike many situations in Python, it is possible to improve parallel performance by exploiting multithreaded parallelism in Python", but "operations on arrays with dtype=np.object_ do not release the GIL"
time, socket, select, threading waits Release it while blocking (the whole point of those calls)
json, re, sorted, str methods, arithmetic Hold it: we measure this in 9.1

What this means for an AI engineer: "which of my steps release the GIL" is the question that decides whether threads help. Network calls, sleeps and database waits do. NumPy, hashing and compression on large buffers do. Your own Python loops, json.loads, regular expressions and pure-Python parsers do not.


Part 3: Measuring it: four demonstrations#

Each script below is complete: save it and run it. The timings are from one machine (macOS, 10 cores, Python 3.14.6, GIL enabled), so read the relationships.

3.1 CPU-bound threads do not scale#

Four identical pure-Python jobs, run one after another, in four threads, and in four processes (01C.1 §2.1 ran the same experiment as a model comparison; here the point is the GIL):

python
# e02_cpu_threads.py: the same pure-Python CPU job run sequentially, in threads and in processes.
import sys
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

N = 4                 # number of identical jobs
WORK = 12_000_000     # loop iterations per job


def crunch(n: int) -> int:
    """Pure-Python arithmetic: holds the GIL the whole time."""
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


def timed(label: str, fn) -> float:
    start = time.perf_counter()
    fn()
    elapsed = time.perf_counter() - start
    print(f"{label:<22} {elapsed:6.2f} s")
    return elapsed


def sequential() -> None:
    for _ in range(N):
        crunch(WORK)


def threads() -> None:
    with ThreadPoolExecutor(max_workers=N) as pool:
        list(pool.map(crunch, [WORK] * N))


def processes() -> None:
    with ProcessPoolExecutor(max_workers=N) as pool:
        list(pool.map(crunch, [WORK] * N))


if __name__ == "__main__":
    gil = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else True
    print("GIL enabled:", gil)
    base = timed("sequential", sequential)
    t = timed(f"{N} threads", threads)
    p = timed(f"{N} processes", processes)
    print(f"threads vs sequential:   x{base / t:.2f}")
    print(f"processes vs sequential: x{base / p:.2f}")
Example output · illustrative6 lines
GIL enabled: True
sequential               1.49 s
4 threads                1.45 s
4 processes              0.54 s
threads vs sequential:   x1.03
processes vs sequential: x2.74

Read it like this:

  • Four threads took as long as no threads at all. Each thread ran its loop only while holding the lock; the lock allowed one at a time; total work was unchanged. On a 10-core machine the extra cores did nothing.
  • Threads are sometimes slower than sequential, not just equal. Lock hand-offs, cache misses when a thread resumes on another core, and the OS scheduler add overhead. On this machine and Python version the difference was within noise; on older versions and with more threads it is often a visible slowdown. If you measure a slowdown, that is the switching cost from 01C.1 Part 5 at work.
  • Four processes gave x2.7, not x4. Each process starts a new interpreter and sends its arguments and result through a pipe (pickling), a fixed cost of the order of a hundred milliseconds that is comparable to the job itself at this size. Make the jobs ten times longer and the ratio moves towards the number of cores. That is Amdahl's law with the start-up cost as the serial part (01C.1 §3.4).

You can prove the "one core" claim without a stopwatch. CPU time (time.process_time) counts every core's work, wall time counts the clock on the wall; their ratio is the number of cores in use (01C.1 §3.2):

python
# ex11_cpu_vs_wall.py: four CPU-bound threads use about one core. CPU time ~ wall time proves it.
import threading
import time


def crunch() -> None:
    total = 0
    for i in range(6_000_000):
        total += i % 7


if __name__ == "__main__":
    wall0, cpu0 = time.perf_counter(), time.process_time()
    threads = [threading.Thread(target=crunch) for _ in range(4)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    wall, cpu = time.perf_counter() - wall0, time.process_time() - cpu0
    print("cores used (cpu/wall):", round(cpu / wall, 1))
    print("about one core:", cpu / wall < 1.5)
Output · Python 3.14.6, GIL build2 lines
cores used (cpu/wall): 1.0
about one core: True

Four busy threads, ten cores available, 1.0 cores used.

3.2 I/O-bound threads do scale#

Now the other half: eight "calls" that each wait 200 ms, standing in for network requests:

python
# e03_io_threads.py: waiting releases the GIL, so threads overlap I/O waits.
import time
from concurrent.futures import ThreadPoolExecutor

N = 8
WAIT = 0.2   # stands in for a 200 ms network call


def fake_call(i: int) -> int:
    time.sleep(WAIT)          # a blocking wait: the GIL is released while we sleep
    return i


start = time.perf_counter()
for i in range(N):
    fake_call(i)
sequential = time.perf_counter() - start

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=N) as pool:
    list(pool.map(fake_call, range(N)))
threaded = time.perf_counter() - start

print(f"sequential: {sequential:.2f} s   (expected about {N * WAIT:.1f})")
print(f"threads:    {threaded:.2f} s   (expected about {WAIT:.1f})")
print("speed-up about", round(sequential / threaded, 1), "x")
Example output · illustrative3 lines
sequential: 1.66 s   (expected about 1.6)
threads:    0.21 s   (expected about 0.2)
speed-up about 7.9 x

Eight waits in parallel took the time of one. The GIL did not interfere at all, because a sleeping thread does not hold it. (Replace time.sleep with requests.get(...) against a real server and the picture is the same. This is why a thread pool is a legitimate way to call a blocking SDK concurrently; see 01B.4 §8.4.)

3.3 One long native call stalls every thread#

The switch interval is only honoured between bytecode instructions. A single long call into native code that does not release the GIL cannot be interrupted. To see the effect we run a heartbeat thread that wakes every millisecond and records how late it was. Being late means it waited for the GIL. The main thread then does different kinds of work:

python
# e05_heartbeat.py: how long does a "heartbeat" thread wait for the GIL while a worker runs?
# The heartbeat wakes every millisecond and records how late it was. Late = it waited for the GIL.
import random
import sys
import threading
import time

BIG = list(range(3_000_000))
random.Random(1).shuffle(BIG)          # shuffled: sorting it is one long C call


def heartbeat(stop: threading.Event, gaps: list[float]) -> None:
    last = time.perf_counter()
    while not stop.is_set():
        time.sleep(0.001)
        now = time.perf_counter()
        gaps.append(now - last - 0.001)      # lateness beyond the 1 ms we asked for
        last = now


def pure_python_worker() -> None:
    total = 0
    for i in range(6_000_000):               # many small bytecodes: the eval loop can be interrupted
        total += i % 7


def one_long_c_call() -> None:
    sorted(BIG)                               # a single C call: holds the GIL until it returns


def sleeping_worker() -> None:
    time.sleep(0.3)                           # blocking wait: the GIL is released


def measure(label: str, worker) -> None:
    stop = threading.Event()
    gaps: list[float] = []
    hb = threading.Thread(target=heartbeat, args=(stop, gaps))
    hb.start()
    time.sleep(0.05)                          # let the heartbeat settle
    gaps.clear()
    worker()                                  # runs in the main thread
    stop.set()
    hb.join()
    print(f"{label:<28} worst heartbeat lateness: {max(gaps) * 1000:7.1f} ms")


if __name__ == "__main__":
    print("switch interval:", sys.getswitchinterval(), "s")
    measure("worker sleeping", sleeping_worker)
    measure("worker in pure Python", pure_python_worker)
    measure("worker in one long C call", one_long_c_call)
    for interval in (0.05, 0.0005):
        sys.setswitchinterval(interval)
        measure(f"pure Python @ {interval * 1000:g} ms", pure_python_worker)
Example output · illustrative6 lines
switch interval: 0.005 s
worker sleeping              worst heartbeat lateness:     0.5 ms
worker in pure Python        worst heartbeat lateness:     8.0 ms
worker in one long C call    worst heartbeat lateness:   535.8 ms
pure Python @ 50 ms          worst heartbeat lateness:    60.6 ms
pure Python @ 0.5 ms         worst heartbeat lateness:     1.3 ms

Five lessons in five lines:

  1. A sleeping worker costs the heartbeat nothing (0.5 ms: scheduler noise). Waiting releases the GIL.
  2. A pure-Python worker delays the heartbeat by about one switch interval (8 ms against the 5 ms default: one interval plus wake-up cost). Python-level code is interruptible every few instructions.
  3. One long native call delays it for the whole call (536 ms here). The drop request could not be honoured until sorted returned. This is the "actual value can be higher, especially if long-running internal functions or methods are used" sentence from the sys docs, measured.
  4. The switch interval controls the lateness for Python-level work: 50 ms gave 60 ms lateness, 0.5 ms gave 1.3 ms.
  5. Lowering it is not free: more frequent hand-offs mean more overhead for the thread doing the work.

The chunking fix, made concrete. Sort 3 million integers as 60 short sorts, pause briefly between them, then merge the sorted runs. The pause must be a real sleep: in a test, time.sleep(0) did not help (the worker re-took the lock before the heartbeat thread could wake, and the heartbeat still stalled for hundreds of milliseconds), so do not rely on it as a yield.

python
# ex_chunked_sort.py: sort in small pieces and really sleep between them, so the heartbeat stays responsive.
import heapq
import random
import threading
import time

DATA = list(range(3_000_000))
random.Random(1).shuffle(DATA)


def heartbeat(stop: threading.Event, gaps: list[float]) -> None:
    last = time.perf_counter()
    while not stop.is_set():
        time.sleep(0.001)
        now = time.perf_counter()
        gaps.append(now - last - 0.001)
        last = now


def one_big_sort() -> None:
    sorted(DATA)                                  # one long C call: holds the GIL throughout


def chunked_sort(chunk: int = 50_000) -> None:
    runs = []
    for start in range(0, len(DATA), chunk):
        runs.append(sorted(DATA[start:start + chunk]))   # short C call (a few ms)
        time.sleep(0.0005)                               # a real (tiny) sleep: waiting threads get in
    for _ in heapq.merge(*runs):                         # merging is pure Python: interruptible
        pass


def worst_lateness(fn) -> float:
    stop = threading.Event()
    gaps: list[float] = []
    hb = threading.Thread(target=heartbeat, args=(stop, gaps))
    hb.start()
    time.sleep(0.05)
    gaps.clear()
    fn()
    stop.set()
    hb.join()
    return max(gaps) * 1000


if __name__ == "__main__":
    print(f"one big sort : worst lateness {worst_lateness(one_big_sort):6.1f} ms")
    print(f"chunked sort : worst lateness {worst_lateness(chunked_sort):6.1f} ms")
Example output · illustrative2 lines
one big sort : worst lateness  483.8 ms
chunked sort : worst lateness   52.2 ms

The long stall drops by roughly ten times. The remaining lateness comes mostly from the pure-Python merge phase, which still competes for the lock (the cost of chunking: slower total time and more code). A process is still the cleaner fix when the whole job is heavy.

To prove the process fix, here is the same measurement with the sort in a worker process. It prints only booleans, so the output is deterministic on an otherwise idle machine (a busy machine can add tens of milliseconds of lateness even without the sort):

python
# ex04_heartbeat_in_process.py: a long C call in a worker PROCESS does not stall the main process.
import multiprocessing as mp
import random
import threading
import time


def long_sort(n: int) -> int:
    data = list(range(n))
    random.Random(1).shuffle(data)
    return len(sorted(data))                 # one long C call, in another process (own GIL)


def worst_lateness_while(fn) -> float:
    stop = threading.Event()
    gaps: list[float] = []

    def heartbeat() -> None:
        last = time.perf_counter()
        while not stop.is_set():
            time.sleep(0.001)
            now = time.perf_counter()
            gaps.append(now - last - 0.001)
            last = now

    hb = threading.Thread(target=heartbeat)
    hb.start()
    time.sleep(0.05)
    gaps.clear()
    fn()
    stop.set()
    hb.join()
    return max(gaps)


if __name__ == "__main__":
    n = 3_000_000
    in_thread = worst_lateness_while(lambda: long_sort(n))
    with mp.Pool(1) as pool:
        in_process = worst_lateness_while(lambda: pool.apply(long_sort, (n,)))
    print("sort in this process stalls the heartbeat (> 100 ms):", in_thread > 0.1)
    print("sort in a worker process does not (< 50 ms):         ", in_process < 0.05)
Output · Python 3.14.62 lines
sort in this process stalls the heartbeat (> 100 ms): True
sort in a worker process does not (< 50 ms):          True

3.4 The convoy effect: an I/O thread behind a CPU thread#

The last demonstration is the subtle one. An I/O-bound thread releases the GIL every time it blocks, then has to ask for it back. If a CPU-bound thread is running, the I/O thread must wait for it to hit the switch interval. A thread that does many short I/O operations pays that wait every time. This pile-up behind a lock holder is called a convoy effect.

The script below does 300 one-byte round trips between two threads over a local socket pair (every recv blocks, so every step is a GIL hand-off), first alone, then with one CPU-bound thread spinning in the background, with the default 5 ms interval and with 0.5 ms:

python
# e11_convoy.py: an I/O-style thread competing with one CPU-bound thread (the convoy effect).
# The "I/O thread" does 300 ping-pongs over a socket pair. Every blocking recv() releases the GIL;
# getting it back means waiting for the CPU thread to hit the switch interval.
import socket
import sys
import threading
import time

ROUNDS = 300


def echo_server(sock: socket.socket) -> None:
    for _ in range(ROUNDS):
        sock.sendall(sock.recv(1))          # bounce one byte back


def ping_pong() -> float:
    a, b = socket.socketpair()
    server = threading.Thread(target=echo_server, args=(b,))
    server.start()
    start = time.perf_counter()
    for _ in range(ROUNDS):
        a.sendall(b"x")
        a.recv(1)
    elapsed = time.perf_counter() - start
    server.join()
    a.close()
    b.close()
    return elapsed


def with_cpu_hog() -> float:
    stop = threading.Event()

    def hog() -> None:
        while not stop.is_set():            # pure-Python spin: always wants the GIL
            sum(i * i for i in range(2_000))

    t = threading.Thread(target=hog)
    t.start()
    try:
        return ping_pong()
    finally:
        stop.set()
        t.join()


if __name__ == "__main__":
    alone = ping_pong()
    print(f"alone:                    {alone * 1000:8.1f} ms for {ROUNDS} round trips")
    for interval in (0.005, 0.0005):
        sys.setswitchinterval(interval)
        busy = with_cpu_hog()
        print(f"CPU thread, interval {interval * 1000:g} ms: {busy * 1000:8.1f} ms  (x{busy / alone:.0f} slower)")
Example output · illustrative3 lines
alone:                         1.6 ms for 300 round trips
CPU thread, interval 5 ms:   4096.1 ms  (x2603 slower)
CPU thread, interval 0.5 ms:    421.7 ms  (x268 slower)

One CPU-bound thread made 300 tiny round trips about 2,600 times slower. Each round trip involves a thread waking up, wanting the GIL, and waiting about one interval for the hog to give it up, on both sides of the conversation. This is an extreme microbenchmark (tiny operations, nothing but hand-offs), but the mechanism is real and has a name in the CPython tracker: issue 7946, "Convoy effect with I/O bound threads and New GIL", reported while 3.2 was in development, measured a large slowdown for a UDP echo test with the new design. Lowering the interval 10x helped about 10x here.

What this means in practice:

  • Never mix a CPU hog and latency-sensitive I/O threads in one process. Run the CPU work in a process pool, or in a separate service.
  • If you must, lower the interval (sys.setswitchinterval(0.0005)), measure, and accept slightly lower CPU throughput. This is a mitigation, not a cure.
  • On a free-threaded build there is no lock to wait for and this effect disappears for pure-Python code (Part 7); this is documentation-based, so measure it on your own free-threaded build (Exercise 1 and Exercise 8 start you off).

What this means for an AI engineer: the typical victim is a service that streams tokens to clients (many tiny I/O steps) while another thread tokenizes, parses or post-processes in pure Python. The stream stutters. Look at the neighbour thread first, not the network.


Part 4: What the GIL protects, and what it does not#

01C.3 owns races in depth; its §2.4 has the full table and §2.5 the official list of atomic operations. The two-line version, so this lesson stands alone:

  • Protected: the interpreter's own consistency. A single operation on a built-in object runs start to finish, so eight threads appending to one list cannot corrupt it.
  • Not protected: your logic. A sequence of operations (x += 1, if k not in d: d[k] = ..., "read the list, then use what you read") can be interleaved at any bytecode boundary.

The first half is easy to see. Eight threads, 100,000 appends each, to one shared list, with no lock:

python
# e06_append_safe.py: what the GIL does guarantee: one append is one indivisible step.
import threading

results: list[int] = []


def worker(base: int) -> None:
    for i in range(100_000):
        results.append(base + i)       # one shared write per item; never corrupts the list


threads = [threading.Thread(target=worker, args=(t * 1_000_000,)) for t in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print("items stored:", len(results))
print("all distinct:", len(set(results)) == 800_000)
# Within each thread's range, items are in order (append order is preserved per thread):
for t in range(3):
    mine = [x for x in results if t * 1_000_000 <= x < (t + 1) * 1_000_000]
    print(f"thread {t} items in order:", mine == sorted(mine))
Output · Python 3.14.65 lines
items stored: 800000
all distinct: True
thread 0 items in order: True
thread 1 items in order: True
thread 2 items in order: True

Nothing was lost or corrupted. The second half is demonstrated in 01C.3: the forced lost update is in its §3.1, and its §2.3 shows honestly that a plain integer += loop may never lose an update on a given build. Do not re-prove it here.

The GIL guarantees The GIL does not guarantee
Built-in containers stay structurally valid under concurrent single operations That d[k] += 1, if x in s: s.remove(x) or total = total + n are atomic
Reference counts are never corrupted Any order between threads
One bytecode instruction (with the C code it calls) is not interleaved That an iteration over a container others modify sees a consistent snapshot
Native extensions that hold the GIL may assume exclusive access to Python objects That native extensions do hold it: they may release it (2.4)
(Today, on the default build) a simple mental model That the model survives: free-threaded builds, and your own future code, may not have it

What this means for an AI engineer: the GIL will not save a shared token budget, a shared cache or a shared conversation list. Treat every shared mutable structure in a threaded AI service as needing its own protection.


Part 5: The escape hatches, compared#

If your work holds the GIL and you need more than one core, you have five options. Four of them are in this part and the next two; the fifth is "use a library whose native code releases the lock" (2.4, Part 8).

flowchart TD
    start["A slow step in my service"] --> q1{"Mostly waiting on network or disk?"}
    q1 -- yes --> io["asyncio or threads: the GIL is released while waiting"]
    q1 -- no --> q2{"Inside a C or Rust library that releases the GIL?"}
    q2 -- yes --> nat["Threads scale: NumPy, hashlib, zlib, tokenizers"]
    q2 -- no --> q3{"Pure Python or holds the GIL?"}
    q3 -- yes --> q4{"Free-threaded build and all dependencies support it?"}
    q4 -- yes --> ft["Threads on python3.14t: measure first"]
    q4 -- no --> q5{"Data cheap to copy, tasks coarse?"}
    q5 -- yes --> proc["ProcessPoolExecutor or InterpreterPoolExecutor"]
    q5 -- no --> shm["Processes plus shared memory: see 01C.7"]
    q3 -- no --> measure["Measure with the scaling harness"]
Option Parallel Python code? Memory Start-up Sharing data Needs
Threads (default build) No (one at a time) Shared, small ~tens of microseconds Direct (and racy: 01C.3) Waiting or GIL-releasing work
Processes (multiprocessing, ProcessPoolExecutor) Yes Each process has its own copy; the largest cost Tens to hundreds of ms Pickle through pipes, or shared memory (01C.7) Picklable arguments and results; the __main__ guard
Subinterpreters (concurrent.interpreters, InterpreterPoolExecutor, 3.14+) Yes (own GIL each) One process; each interpreter has its own modules and objects Faster than a process, slower than a thread (the 3.14 release notes list that "starting each interpreter has not been optimized yet") Copy (pickle) or memoryview; opt-in sharing 3.14+; extension modules that support isolated interpreters (Part 6)
Free-threaded CPython (3.13t / 3.14t / 3.15t) Yes (no GIL) Shared, a bit higher than the default build Same as threads Direct, with per-object locks inside built-ins; your own locks for your logic A free-threaded build and extensions that support it (Part 7)
Native code that releases the GIL Only inside the native part Shared n/a Direct A library that does it (NumPy, hashlib, zlib, many Rust-backed packages)

5.1 Processes: the proven answer#

For the pool-initializer pattern and the start-method details (spawn, forkserver, fork), see 01C.7 §9.2 and §1.5.

The Python FAQ's own advice for multi-core machines is processes: "You just have to be creative with dividing the work up between multiple processes rather than multiple threads. The ProcessPoolExecutor class in the concurrent.futures module provides an easy way of doing so; the multiprocessing module provides a lower-level API in case you want more control over dispatching of tasks." Each process has its own interpreter and its own GIL.

A realistic shape: a batch of documents to analyse, cut into a few large chunks so that pickling a task costs less than doing it:

python
# ex05_wordcount_pool.py: count words in many documents with a process pool (a CPU-bound batch).
from collections import Counter
from concurrent.futures import ProcessPoolExecutor

DOCS = [f"refund request order {i % 5} refund approved order {i % 3}" for i in range(2_000)]


def count_chunk(chunk: list[str]) -> Counter[str]:
    total: Counter[str] = Counter()
    for doc in chunk:
        total.update(doc.split())
    return total


def chunked(items: list[str], size: int):
    for i in range(0, len(items), size):
        yield items[i : i + size]            # a few big tasks, not 2,000 tiny ones: less pickling


if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=4) as pool:
        partials = pool.map(count_chunk, chunked(DOCS, 500))
        total = sum(partials, Counter())
    print(total.most_common(3))
    print("same as one process:", total == count_chunk(DOCS))
Output · Python 3.14.62 lines
[('refund', 4000), ('order', 4000), ('request', 2000)]
same as one process: True

The rules that make a process pool pay off, in order of how often they bite:

  1. Coarse tasks. Every task's arguments and result are pickled and copied through a pipe. A task that takes a microsecond and carries a kilobyte loses to a plain loop. Batch (01B.4 §5.2).
  2. Guard the entry point with if __name__ == "__main__": under spawn (Windows, macOS) and forkserver (Linux and other Unix from 3.14); only fork (the older Linux default) lets you forget it, and fork is unsafe with threads (01C.4). Without the guard, each worker re-imports your script and tries to start a pool of its own.
  3. Mind the start method. As of Python 3.14, on Unix other than macOS the default start method is forkserver (it was fork); Windows and macOS keep spawn. The 3.14 release notes say to request fork explicitly through get_context() if you depend on it. 01C.7 owns the details.
  4. Load big read-only data once per worker, not per task (the initializer argument). 01C.7 shows the pattern and the shared-memory alternative.
  5. Memory multiplies. Four workers holding a 2 GB model need roughly 8 GB unless the data is shared (01C.6 explains why copy-on-write sharing after fork is weaker in Python than in C).

01B.4 §8.6 has the short practical recipe; this lesson explains why it is needed.

5.2 Threads still win for waiting work#

Do not leave this lesson thinking threads are bad. For anything that is mostly waiting (a blocking SDK, a database driver, a subprocess), threads are cheaper than processes, share memory, and the GIL does not get in the way (3.2). The rule: threads for waiting, processes (or native code) for computing, asyncio for waiting at scale (01C.1 §6.1).

What this means for an AI engineer: a service has both kinds of work. The standard architecture is an asyncio (or threaded) front end for the I/O fan-out, a process pool or a separate worker service for the CPU stages (PDF parsing, chunk normalisation), and native libraries for the heavy numeric parts.


Part 6: Subinterpreters: one GIL per interpreter#

Deep-dive

6.1 The idea#

A process can contain more than one Python interpreter. Each subinterpreter has its own modules, its own globals, its own builtins (even its own sys and __main__), and, since Python 3.12, can have its own GIL (PEP 684, Final, 3.12). Two subinterpreters in two threads can therefore run Python code on two cores at the same time, inside one process, without the memory duplication and pipes of separate processes.

Subinterpreters have long existed in the C API, and since 3.12 each can have its own GIL, but there was no Python-level API: you needed C. Python 3.14 added one: PEP 734 (Final) provides the concurrent.interpreters module and concurrent.futures.InterpreterPoolExecutor. The 3.14 release notes describe the model well: "Think of multiple interpreters as threads but with opt-in sharing."

What had to be isolated to make this work (PEP 684): the interpreter's runtime state, the small-object memory allocator state, the garbage collector, warnings and atexit hooks. What is still shared: the process itself (memory, file descriptors, environment variables), and immutable singletons made safe by immortal objects (PEP 683, 3.12).

6.2 concurrent.interpreters in practice#

The API (3.14): interpreters.create(), interp.exec(source) (runs source text in that interpreter's __main__; it is synchronous), interp.call(func, *args), interp.call_in_thread(func), interp.prepare_main(**kwargs) (put values into its __main__), interpreters.create_queue() (a queue that can be shared), interp.close(), and the exceptions ExecutionFailed and InterpreterError.

python
# e08_interpreters.py: subinterpreters in the standard library (Python 3.14+, PEP 734).
from concurrent import interpreters

counter_code = """
count = globals().get("count", 0) + 1     # lives in THIS interpreter's __main__ only
"""

main_marker = "set in the main interpreter"

interp_a = interpreters.create()
interp_b = interpreters.create()

# exec() runs source text in that interpreter's __main__; state persists between calls.
for _ in range(3):
    interp_a.exec(counter_code)
interp_b.exec(counter_code)

# Interpreters share nothing by default. Send data through a Queue (copied, not shared).
q = interpreters.create_queue()
interp_a.prepare_main(q=q)
interp_b.prepare_main(q=q)
interp_a.exec("q.put(('a', count))")
interp_b.exec("q.put(('b', count))")
print("counts per interpreter:", sorted([q.get(), q.get()]))

# The main interpreter's globals are invisible inside:
interp_a.exec("q.put('main_marker' in globals())")
print("main_marker visible inside a subinterpreter:", q.get())


# call() runs a callable in the interpreter. In the 3.14.x we ran, it accepts arguments and
# returns the result (the PEP text said no arguments and discarded results: see the lesson).
def shout(text: str) -> str:
    return text.upper()


print("call() result:", interp_b.call(shout, "refund approved"))
print("call() with a builtin:", interp_b.call(pow, 2, 10))

# An uncaught exception inside arrives as ExecutionFailed, not as the original class.
try:
    interp_a.exec("1 / 0")
except interpreters.ExecutionFailed as exc:
    print("ExecutionFailed first line:", str(exc).splitlines()[0])

interp_a.close()
interp_b.close()
print("interpreters left:", len(interpreters.list_all()))
Output · Python 3.14.66 lines
counts per interpreter: [('a', 3), ('b', 1)]
main_marker visible inside a subinterpreter: False
call() result: REFUND APPROVED
call() with a builtin: 1024
ExecutionFailed first line: ZeroDivisionError: division by zero
interpreters left: 1

What it shows: each interpreter kept its own count (3 and 1: state persists between exec calls, and is invisible to the other); the main interpreter's global main_marker does not exist inside; a queue carried values across; an exception inside surfaced as ExecutionFailed, not as a ZeroDivisionError object. (list_all() returns 1: only the main interpreter is left.)

6.3 InterpreterPoolExecutor: the drop-in#

For CPU-bound work you rarely want the low-level API. InterpreterPoolExecutor has the same interface as the other executors (submit, map, context manager): "a ThreadPoolExecutor subclass" in which "each thread runs tasks in its own interpreter", so "code run with this executor has true multi-core parallelism". Callable and arguments are pickled to get into the worker interpreter, and the result is pickled back, as with processes.

python
# e09_interpreter_pool.py: CPU-bound work on threads, subinterpreters and processes (Python 3.14+).
import sys
import time
from concurrent.futures import InterpreterPoolExecutor, ProcessPoolExecutor, ThreadPoolExecutor

N = 4
WORK = 12_000_000


def crunch(n: int) -> int:
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


def run(label: str, executor_cls) -> float:
    start = time.perf_counter()
    with executor_cls(max_workers=N) as pool:
        results = list(pool.map(crunch, [WORK] * N))
    elapsed = time.perf_counter() - start
    print(f"{label:<28} {elapsed:5.2f} s   results equal: {len(set(results)) == 1}")
    return elapsed


if __name__ == "__main__":
    print("GIL enabled:", sys._is_gil_enabled())
    t = run("ThreadPoolExecutor", ThreadPoolExecutor)
    i = run("InterpreterPoolExecutor", InterpreterPoolExecutor)
    p = run("ProcessPoolExecutor", ProcessPoolExecutor)
    print(f"interpreters vs threads: x{t / i:.1f}   processes vs threads: x{t / p:.1f}")
Example output · illustrative5 lines
GIL enabled: True
ThreadPoolExecutor            1.50 s   results equal: True
InterpreterPoolExecutor       0.57 s   results equal: True
ProcessPoolExecutor           0.65 s   results equal: True
interpreters vs threads: x2.6   processes vs threads: x2.3

Same code, same GIL-enabled build, and the interpreter pool ran the CPU job in parallel: the threads shared one GIL, the interpreters each had their own. Here it also edged out processes, because starting an interpreter is cheaper than starting a process; at larger sizes the two converge.

6.4 The limits (from the documentation)#

Limit Detail
Extension modules must opt in A C extension must be written for multiple interpreters (multi-phase initialisation, PEP 489). The Python FAQ names this as the main limit: "many older extension modules will not be usable". Check each dependency
Nothing mutable is shared "a mutable object, or other data, cannot be used by more than one interpreter at the same time"; each interpreter needs its own copy. Immutable data (strings, tuples of immutables, builtin singletons) is fine. Objects supporting the buffer protocol (memoryview) can share memory with no race protection
Heavier than threads The 3.14 release notes (current limitations) list: starting each interpreter "has not been optimized yet"; "each interpreter uses more memory than necessary"; and "there aren't many options yet for truly sharing objects or other data between interpreters (other than memoryview)"
Pickling InterpreterPoolExecutor pickles callables, arguments and results; so the same "must be picklable" rule as for processes
Communication goes through queues The module's way to pass data between interpreters is the cross-interpreter Queue (concurrent.interpreters.create_queue()); because nothing mutable is shared, there is no shared state to lock
Not a security boundary The docs: "do not use multiple interpreters in security-sensitive situations, where they shouldn't have access to each other's data" (extension modules can break the isolation)
Young Standard-library support began in 3.14 (October 2025). Expect rough edges in third-party code as of November 2026
Check support sys.implementation.supports_isolated_interpreters is True on a build that has them (we saw True). Importing concurrent.interpreters on an implementation without them raises ImportError

What this means for an AI engineer: subinterpreters are the lightweight middle between threads and processes for pure-Python CPU stages (cleaning, chunk splitting, custom scoring) when your dependencies are compatible. For anything that imports a large scientific stack, a process pool is still the safer choice as of November 2026: verify each package before committing.


Part 7: Free-threaded CPython: the build without a GIL#

Deep-dive

7.1 What it is, and its official status#

Free-threaded CPython is a build of the reference interpreter that runs with the GIL disabled, so threads execute Python bytecode truly in parallel. It is the result of PEP 703, "Making the Global Interpreter Lock Optional in CPython", by Sam Gross. The PEP's own motivation is notable for this course: it says the GIL "is a major obstacle to concurrency" and that scientific and AI workloads are the most affected, citing PyTorch developers and reinforcement-learning teams whose threads stop scaling and who fall back to multiprocessing or C++.

The status, as of November 2026, from the official sources:

Fact Source
Python 3.13 (October 2024) added the free-threaded build as experimental ("phase I" of PEP 703) PEP 779 recaps the phases
Python 3.14 (October 2025): PEP 779 (Final, resolved 16 June 2025) made it officially supported but still optional: "phase II". "Free-threaded Python is officially supported" PEP 779; 3.14 release notes; the FAQ ("officially supported as of Python 3.14, but is not the default build")
Phase III, making the free-threaded build the default, has no date: PEP 779 says the decision "will depend on community support, willingness, and clear benefit, to be settled in a future PEP" PEP 779
Python 3.15 (released 9 October 2026) did not change the default: it adds a Stable ABI for free-threaded builds (PEP 803, abi3t), and "the official macOS binaries now install free-threading support by default" What's New in Python 3.15
The build is a separate executable; the GIL build is still what python3 normally gives you free-threading HOWTO

PEP 779's criteria for phase II set a hard target of at most 15% single-thread slowdown (the PEP reported about 10% at the time, about 3% on macOS) and at most 20% more memory. The 3.14 release notes say the single-thread penalty "is now roughly 5-10%, depending on the platform and C compiler used"; the HOWTO says "the average overhead ranges from about 1% on macOS aarch64 to 8% on x86-64 Linux systems" on the pyperformance suite.

7.2 How it works (so the trade-offs make sense)#

Removing the lock means refcounts and built-in containers need another way to stay safe. PEP 703's design, in the PEP's words:

Mechanism What it does
Biased reference counting Each object has an owner thread that updates a local count with no atomic operations; other threads use a shared atomic count. Most objects are touched by one thread, so most increments stay cheap
Immortalization Objects that live for the whole program (small integers, None, interned strings) skip reference-count updates entirely, so there is no contention on them. The HOWTO notes that in 3.14 immortalization is limited to code constants and sys.intern() strings
Deferred reference counting Frequently shared objects (module objects, top-level functions, methods) skip some count updates and are freed only when the garbage collector runs
mimalloc Replaces pymalloc as the thread-safe allocator: "The free-threaded build does not use pymalloc and allocates all Python objects using the 'mimalloc' allocator"
Per-object locks and critical sections list, dict and set carry a lightweight lock; C code uses Py_BEGIN_CRITICAL_SECTION macros that may release locks around blocking operations to avoid deadlocks
Stop-the-world GC Threads pause for cycle detection
Specialising interpreter Enabled in free-threaded mode in 3.14 (PEP 659), one of the reasons the penalty shrank

7.3 Installing it and checking which build you run#

From the HOWTO: "Starting with Python 3.13, the official macOS and Windows installers optionally support installing free-threaded Python binaries" (python.org/downloads); building from source uses ./configure --disable-gil; other platforms are covered by the community guide linked from the HOWTO. With uv, the documentation says it "supports discovering and installing free-threaded Python variants in CPython 3.13+" with request forms such as 3.14t or 3.14+freethreaded:

bash
uv python install 3.14t
uv run --python 3.14t python e07_gil_report.py

(The uv page documents the <version>t request format; the exact uv python install 3.14t line follows from it. As with everything installable, do it in a throw-away project, not in a production environment.)

Identify the build and the runtime state with the two checks the HOWTO recommends, which are different questions: sysconfig.get_config_var("Py_GIL_DISABLED") ("the recommended mechanism for decisions related to the build configuration") and sys._is_gil_enabled() ("check whether the GIL is actually disabled in the running process"). python -VV also contains "free-threading build" on such a build.

python
# e07_gil_report.py: which kind of CPython is this, and is the GIL on right now?
import os
import sys
import sysconfig

build_is_free_threaded = sysconfig.get_config_var("Py_GIL_DISABLED") == 1   # what the build supports
gil_now = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else True  # 3.13+; older: always on

print("implementation:       ", sys.implementation.name)
print("free-threaded build:  ", build_is_free_threaded)
print("GIL enabled right now:", gil_now)
print("PYTHON_GIL variable:  ", os.environ.get("PYTHON_GIL", "(not set)"))
print("switch interval (s):  ", sys.getswitchinterval())
print("subinterpreters:      ", getattr(sys.implementation, "supports_isolated_interpreters", "unknown"))
print("thread_inherit_context:", getattr(sys.flags, "thread_inherit_context", "n/a"))
Output · Python 3.14.6, normal build7 lines
implementation:        cpython
free-threaded build:   False
GIL enabled right now: True
PYTHON_GIL variable:   (not set)
switch interval (s):   0.005
subinterpreters:       True
thread_inherit_context: 0
Example output · illustrative7 lines
implementation:        cpython
free-threaded build:   True
GIL enabled right now: False
PYTHON_GIL variable:   (not set)
switch interval (s):   0.005
subinterpreters:       True
thread_inherit_context: 1

7.4 Controlling the GIL at run time#

A free-threaded build can run with the GIL: the HOWTO says it supports "optionally running with the GIL enabled at runtime using the environment variable PYTHON_GIL or the command-line option -X gil". PYTHON_GIL=1 (or -X gil=1) forces it on; 0 forces it off. Useful for A/B-testing a regression: is the bug the removal of the GIL or something else?

bash
PYTHON_GIL=1 python3.14t e07_gil_report.py    # free-threaded build, GIL forced on
python3.14t -X gil=0 e07_gil_report.py        # GIL off, even if an extension asked for it back

The reverse does not work. On a normal build the request is refused outright. This is real output from our GIL-only 3.14.6:

console
$ PYTHON_GIL=0 python3 -c "pass"
Output · Python 3.14.6, normal build2 lines
Fatal Python error: config_read_gil: Disabling the GIL is not supported by this build
Python runtime state: preinitialized

And in a free-threaded build, importing a C extension that does not declare free-threading support re-enables the GIL for the rest of the process. The HOWTO: "The GIL may also automatically be enabled when importing a C-API extension module that is not explicitly marked as supporting free threading. A warning will be printed in this case." PEP 703 describes the mechanism: an extension declares support with the Py_mod_gil slot set to Py_MOD_GIL_NOT_USED (3.13+); with no slot the default is Py_MOD_GIL_USED, and the interpreter re-enables the GIL.

python
# ex07_require_free_threaded.py: a start-up guard for code that is only worth running without the GIL.
import sys
import sysconfig


def gil_status() -> str:
    if not hasattr(sys, "_is_gil_enabled"):
        return "unknown: Python older than 3.13 (the GIL is always on)"
    if sys._is_gil_enabled():
        if sysconfig.get_config_var("Py_GIL_DISABLED") == 1:
            return "free-threaded build, but the GIL is ON (PYTHON_GIL=1, or an extension re-enabled it)"
        return "normal build: the GIL is on"
    return "free-threaded build, GIL off: threads run Python in parallel"


print(gil_status())
Output · Python 3.14.6, normal build1 line
normal build: the GIL is on

7.5 How to check whether a package supports free threading#

Three levels of evidence, cheapest first:

  1. Pure-Python packages (no compiled extension) work without a GIL, because nothing in them re-enables it. Their thread safety is another matter (01C.3).
  2. Compiled packages: look for a wheel for the free-threaded ABI. Free-threaded builds use their own wheel tag (cp314t, as in cp314t-...); a package with only cp314 wheels will be built from source or will load an extension that re-enables the GIL. The community trackers named in the HOWTO list status per package: py-free-threading.github.io/tracking and hugovk.github.io/free-threaded-wheels.
  3. Test it yourself: on the free-threaded interpreter, import the package in a fresh process and check the flag afterwards. A package that re-enables the GIL prints a warning and flips sys._is_gil_enabled() back to True.
bash
# Illustrative: run on a free-threaded interpreter (python3.14t). Replace some_package.
python3.14t -c "import some_package, sys; print('GIL after import:', sys._is_gil_enabled())"
Example output · illustrative1 line
GIL after import: False

If it prints True (with a warning above it), that package, or one it imports, does not declare support. NumPy's own documentation says it has "experimental support" for GIL-disabled runtimes, "starting with NumPy 2.1 and CPython 3.13" (as of November 2026 that page still calls it experimental; check the current NumPy release notes), and warns that dtype=np.object_ arrays "are not protected by the GIL, creating data races for python objects that are not possible outside free-threaded python".

7.6 What changes for your own code#

01C.3 §8.9 lists the race-related consequences; the short version:

  • Your locks matter more. Code that was "correct" because the GIL happened to serialize a multi-step sequence loses that accident. Built-ins keep their internal locks, so single operations stay safe; multi-step logic needs your own lock.
  • Iterators "generally not thread-safe to access the same iterator object from multiple threads concurrently", and threads "may see duplicate or missing elements".
  • sys.flags.thread_inherit_context and context_aware_warnings default to on in the free-threaded build (so threads inherit the contextvars context and catch_warnings becomes thread-aware); they default to off in the GIL build.
  • Memory is higher. On AMD64 None takes 32 bytes on the free-threaded build against 16 on the default one (HOWTO); interned strings become immortal; mimalloc can delay returning memory to the OS (MIMALLOC_PURGE_DELAY=0 changes that at a performance cost); gc.collect() merges per-thread counts so frozen objects can be freed.
  • A sharp edge: "It is not safe to access frame.f_locals from a frame object if that frame is currently executing in another thread, and doing so may crash the interpreter." Debuggers and profilers that poke at other threads' frames need free-threading-aware versions.
  • Contention replaces the GIL: a single hot lock-protected object (the global random generator, one big dict) can become the new bottleneck. Design for sharding or per-thread state.

7.7 Should you use it?#

As of November 2026, with the usual caveat that this moves fast:

Situation Advice
Your AI service is I/O-bound (LLM calls, retrieval, streaming) No reason to switch. asyncio or threads already work; free threading adds memory and risk for no gain
You have CPU-heavy pure-Python stages and control all dependencies Worth a measured trial: run the scaling harness (9.1) on the free-threaded build; you may replace a process pool with threads and drop pickling
Your stack depends on many compiled packages Check each (7.5). One that re-enables the GIL nullifies the build
You write a library Test on both builds and declare support honestly; the community porting guide is at py-free-threading.github.io
You need parallelism today with low risk Processes (or InterpreterPoolExecutor with checked dependencies)

What this means for an AI engineer: keep an eye on the two ecosystem questions (does my vector client, tokenizer and parser support it?) and write thread-safe code regardless. The direction of travel is clear, the default build has not changed, and "wait for your dependencies" is the honest advice.


Part 8: Other implementations and native-code awareness#

Reference

8.1 Other Python implementations#

Implementation GIL? Notes (as of November 2026)
CPython Yes by default; optional free-threaded build The reference implementation; everything above
PyPy Yes: the FAQ says "Yes, PyPy has a GIL. Removing the GIL is very hard." Software-transactional-memory work to remove it "is currently a bit stalled" A JIT: often much faster for pure-Python loops, but still one thread at a time
GraalPy Yes: "GraalPy implements the Python global interpreter lock (GIL)"; it releases it by default when calling out to other languages Runs on the JVM/GraalVM; it targets a recent Python 3.x release; check the GraalPy docs for the exact version
Jython No GIL: it runs on the JVM and uses JVM threads (the python.org wiki page on the GIL lists Jython and IronPython as having none) The homepage says the current release "only supports Python 2"; Python 3 support is "in development": not usable for Python 3.11+ code
IronPython No GIL: it runs on .NET threads (same wiki page), with fine-grained locking inside built-in types Targets an older Python 3 than this course's 3.11+ baseline; check the project for its current version

Practical point: for the 3.11+ code in this course, CPython is the implementation that matters. The rows are awareness, so you can answer "does Python have a GIL?" with "CPython and PyPy do; whether another implementation does, check it".

8.2 Native code that releases the GIL: what it looks like#

You will not write this in this course, but you will depend on it, so here is what the libraries do (illustrative, none of this was run):

python
# Illustrative (Numba is third-party, not run here): nogil=True releases the GIL for the whole function.
from numba import njit


@njit(nogil=True)            # compiled to machine code; threads can run it in parallel
def dot_loop(a, b):
    total = 0.0
    for i in range(a.shape[0]):
        total += a[i] * b[i]
    return total
Tool How it releases the GIL
C extension Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS around the long, Python-object-free part (2.4)
Cython with nogil: blocks (the body may not touch Python objects)
Numba @njit(nogil=True) as above
Rust with PyO3 Python::detach runs a closure with the interpreter detached (it was called allow_threads before PyO3 0.26, which renamed it; see the PyO3 guide on parallelism)
ctypes foreign calls through ctypes.CDLL release the GIL for the duration of the call; ctypes.PyDLL does not (the docs: the lock "is released before calling any function exported by these libraries, and reacquired afterwards"), so use CDLL for slow shared-library calls
NumPy and similar internal: "Many NumPy operations release the GIL"
Rust tokenizers, ONNX/ML runtimes, database drivers usually release it while running native inference or waiting for the server; check each project's notes

The pattern for using such a library: wrap the call in a thread pool and measure (9.1). If four threads give x3 or more, the library releases the GIL for that call. If they give x1, it does not, and a process pool is next.

What this means for an AI engineer: most of the heavy lifting in an AI stack (tensor math, ONNX inference, tokenizers, vector search clients) is native, and most of it is designed to run well alongside Python threads. The GIL bites hardest in the glue you write yourself in pure Python.


Part 9: How to measure whether the GIL is your problem#

The wrong order is "I heard Python has a GIL, so I will use processes". The right order is: measure, find the bottleneck, then pick the cheapest fix. Four tools, cheapest first.

9.1 The scaling harness: measure, don't guess#

The most direct test is the one used throughout this lesson: run the same function in 1 thread, then in N threads at once, and compare. If N copies take about as long as one, the function scales. If N copies take N times as long, the GIL (or another shared resource) serialises them.

python
# e10_scaling_harness.py: does this function scale across threads? Measure instead of guessing.
import hashlib
import json
import re
import sys
import time
import zlib
from concurrent.futures import ThreadPoolExecutor

BLOB = b"support ticket: customer cannot reset password; " * 400_000   # about 19 MB
TEXT = BLOB.decode()
DOC = json.dumps([{"id": i, "text": "refund request", "tags": ["a", "b"]} for i in range(60_000)])
WORDS = [str(hash(str(i)) % 100_000) for i in range(300_000)]


def pure_python() -> None:
    total = 0
    for i in range(1_500_000):
        total += i * i % 7


def sha256() -> None:
    hashlib.sha256(BLOB).hexdigest()


def zlib_compress() -> None:
    zlib.compress(BLOB, 6)


def json_loads() -> None:
    json.loads(DOC)


def regex_findall() -> None:
    re.findall(r"password", TEXT)


def list_sort() -> None:
    sorted(WORDS)


def sleep_wait() -> None:
    time.sleep(0.15)


def wall(fn, workers: int) -> float:
    """Run `workers` copies of fn at once; return elapsed wall-clock seconds."""
    start = time.perf_counter()
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(fn) for _ in range(workers)]
        for f in futures:
            f.result()
    return time.perf_counter() - start


def scaling(fn, workers: int = 4) -> float:
    """Speed-up of `workers` threads over doing the same total work one after another."""
    one = min(wall(fn, 1) for _ in range(5))         # time of a single copy
    many = min(wall(fn, workers) for _ in range(5))  # time of `workers` copies in parallel
    return workers * one / many                      # ideal answer: workers


if __name__ == "__main__":
    gil = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else True
    print("GIL enabled:", gil, "| 4 threads, ideal speed-up = 4.0")
    for fn in (pure_python, json_loads, regex_findall, list_sort, sha256, zlib_compress, sleep_wait):
        s = scaling(fn)
        verdict = "scales" if s > 2.5 else ("partly" if s > 1.4 else "GIL-bound")
        print(f"{fn.__name__:<14} x{s:4.1f}  {verdict}")
Example output · illustrative8 lines
GIL enabled: True | 4 threads, ideal speed-up = 4.0
pure_python    x 1.0  GIL-bound
json_loads     x 0.9  GIL-bound
regex_findall  x 1.0  GIL-bound
list_sort      x 1.0  GIL-bound
sha256         x 3.8  scales
zlib_compress  x 3.7  scales
sleep_wait     x 4.0  scales

This is the empirical answer to "which standard-library calls release the GIL": hashing and compression of a large buffer and sleeping scale; the pure-Python loop, json.loads, re.findall and sorted do not, even though three of those four are implemented in C. Run the same file on a free-threaded build and, per the documentation, the first four rows should move towards x4 (the numbers are for you to measure; none were measured here).

Two cautions when you use the harness on your own function:

  • Warm up and repeat. The first sample is often an outlier (caches, memory allocation, other processes), so the harness takes the minimum of five runs; use more repeats for a decision that matters. The verdict thresholds (2.5 and 1.4) are rough: a borderline row such as x1.8 deserves a second run before you decide.
  • Beware shared resources that are not the GIL. A function that scales badly may be limited by memory bandwidth, a lock inside a library, or a rate limit, not by the GIL. The harness tells you whether it scales, not why. The next tools say why.

9.2 CPU time versus wall time, and the heartbeat#

Two cheap diagnostics from earlier in this lesson, repeated here as tools:

  • time.process_time() divided by wall time (3.1, 01C.1 §3.2): about 1.0 for many busy threads means they are sharing one core's worth of Python execution; close to 0 means they mostly wait.
  • The heartbeat thread (3.3): a thread that wakes every millisecond and records its lateness is a live detector of "somebody is holding the GIL". Put a version of it behind a debug flag in a threaded service. (The asyncio equivalent is the loop-lag monitor in 01C.2 §8.2.)

To catch the culprit rather than the symptom, faulthandler.dump_traceback_later and sys._current_frames() show what every thread is doing at a moment (01C.4 builds a watchdog from them): the thread whose frame sits in your pure-Python loop or a long native call is the one holding the lock.

9.3 Profilers that know about the GIL#

  • py-spy (third-party, a sampling profiler that attaches to a running process without modifying it; not run here): its record command has a --gil option that includes only samples from threads holding the GIL, and py-spy dump prints every thread's stack. This is the best way to look at a production process. Check py-spy --help for the options in your version.
  • Python 3.15's built-in sampling profiler (called Tachyon in its documentation): the 3.15 release notes say it has a GIL-holding time mode, --mode gil, that "measures time spent holding Python's Global Interpreter Lock". Read the What's New page for the exact command line.
  • A scientific-Python note: inside NumPy-heavy code, a normal profiler cannot see native time well; wall-time scaling (9.1) is the reliable test.

9.4 A measuring checklist#

  1. Is the step I/O-bound or CPU-bound? (CPU time versus wall time.) If I/O-bound, the GIL is not your problem.
  2. If CPU-bound, run the scaling harness: does it scale across threads? If yes, you are already fine: use threads.
  3. If not, is it a library call or your own Python? A library call that does not scale may have a documented option or a newer release that releases the GIL.
  4. Try a process pool on coarse chunks; measure the real speed-up including pickling and start-up.
  5. Only then consider subinterpreters or a free-threaded build, and verify every dependency.
  6. Re-measure under realistic load (the convoy effect and contention show up only with concurrent neighbours).

Part 10: Choosing for AI workloads#

The decision table. "Typically" means the pattern is common in the ecosystem but you must confirm it for your library and version with the harness (9.1). Rows that quote a speed-up come from the illustrative run in 9.1 on the standard library; those numbers vary from run to run, so treat them as orders of magnitude, not benchmarks.

Workload Nature Threads on the default build? Best default choice Notes
LLM and embedding API calls Waiting on the network Yes (GIL released while waiting) asyncio with a bound (01B.4); threads for blocking SDKs The GIL is irrelevant
Streaming tokens to clients Many tiny I/O steps Yes, but sensitive to CPU neighbours (3.4) asyncio; keep CPU work out of the process The convoy effect hits here
Hashing and checksums (dedupe by content hash) CPU, in native code Yes for large inputs (typically x3 to x4 in the 9.1 run) Threads hashlib releases the GIL above 2047 bytes
Compression (zlib, gzip) CPU, in native code Yes (typically x3 to x4 in the 9.1 run) Threads The FAQ names zlib
NumPy / matrix maths, cosine similarity on arrays CPU, native Typically yes for large arrays ("Many NumPy operations release the GIL") Threads, or NumPy's own threaded BLAS Not for dtype=object arrays
Local embedding or ONNX inference CPU or GPU, native runtime Typically yes One process with intra-op threads; processes for isolation Check the runtime's thread settings; avoid oversubscription (01C.1 §5.7)
Tokenizing with Rust-backed tokenizers CPU, native Typically yes for batch calls Threads or the library's own batch API Verify with the harness; pure-Python tokenizers do not
Counting tokens one string at a time in a Python loop Small calls in a loop Little gain: per-call overhead and lock traffic dominate Batch the calls; processes if it is a big batch See 06.2 for batching
PDF parsing with pure-Python libraries (pdfminer, pypdf, pdfplumber) CPU, Python bytecode No Process pool, shard by file or page range 05.2 §10.3 says the same: parsing is CPU-bound and pages are independent
PDF parsing with native engines (PyMuPDF, pypdfium2) CPU, native Depends on the binding Measure; processes are the safe default Native does not imply released (2.4)
JSON parsing (json.loads) CPU, holds the GIL No (about x1 in the 9.1 run) Processes for huge payloads; stream and chunk A faster third-party parser is faster per call, but check whether it releases the lock
Regular expressions (re) CPU, holds the GIL No (about x1 in the 9.1 run) Processes; or rewrite the hot pattern Catastrophic backtracking is also a latency bug on its own
Sorting or de-duplicating huge lists CPU, holds the GIL No (about x1 in the 9.1 run) Processes, or push to NumPy / the database One long C call blocks every thread (3.3)
Text cleaning and chunking in pure Python CPU, bytecode No Process pool on coarse batches; subinterpreters if dependencies allow 05.5 and 05.6 give the algorithms
Writing to a database or vector store Waiting Yes Threads or async client Connection pool size is the limit, not the GIL

A worked reading of the table: an ingestion job downloads 50,000 PDFs, parses them, cleans the text, embeds the chunks, and writes vectors. Download: asyncio or threads. Parse and clean: a process pool over files. Embed: batched API calls, async with a bound (or a native runtime). Write: a bounded async or threaded writer. The GIL decides exactly one of those four steps (parse and clean), and the answer is processes. 01C.1 §3.3 runs this exact shape with timings.


Reference
Symptom Cause Fix
Adding threads to a parsing job changed nothing, or made it slower Pure-Python CPU work serialised by the GIL, plus switching overhead (3.1) Process pool on coarse chunks; measure with the harness first (9.1)
The whole service freezes for a fraction of a second at random, including health checks One request ran a long GIL-holding call (sorted, json.loads, a big regex, pandas merge) (3.3) Move the call to a process, chunk it, or use a library that releases the lock; add a heartbeat or loop-lag monitor
Token streaming stutters when a background thread tokenizes or post-processes The convoy effect: the I/O threads wait up to a switch interval each time (3.4) Separate CPU work from the I/O process; lower sys.setswitchinterval as a stop-gap
ProcessPoolExecutor made a tiny task slower Pickling and pipe cost exceed the work (5.1) Batch into coarse chunks
A script that works on Python 3.13 on Linux hangs or re-runs itself on Windows, macOS or 3.14+ Linux with a process pool Missing if __name__ == "__main__": guard under spawn or forkserver (5.1) Add the guard (01C.7)
PYTHON_GIL=0 crashes at start-up with "Disabling the GIL is not supported by this build" The interpreter is a normal build, not a free-threaded one (7.4) Install a free-threaded build (python3.14t), or drop the variable
On a free-threaded build the code is still not parallel An imported extension re-enabled the GIL (7.4) Print sys._is_gil_enabled() after imports; find the offending package (7.5)
A race that "never happened" starts showing up after moving to a free-threaded build Code that was only correct because the GIL serialised it (Part 4, 7.6) Add locks around multi-step logic (01C.3)
InterpreterPoolExecutor raises on import of a package inside a worker The extension module does not support isolated interpreters (6.4) Use a process pool for that stage
Memory use doubled after moving a service to a free-threaded build Larger object headers, mimalloc retention (7.6) Measure; try MIMALLOC_PURGE_DELAY=0 and gc.collect() after bursts; right-size

Common misconceptions#

Misconception Reality
"Python can't do multithreading" It can: threads are real OS threads and overlap all waiting work. Only Python bytecode execution is serialised, on the default build (3.2)
"The GIL means Python uses one core" One process's Python code runs on one core at a time. Processes, native code that releases the lock, and subinterpreters use many (Part 5, Part 6)
"Python 3.14 removed the GIL" 3.14 made the optional free-threaded build officially supported (PEP 779). The default build still has the GIL; making free-threading the default is undecided (7.1)
"The GIL makes my code thread-safe" It protects the interpreter, not your multi-step logic, and it only exists on one build (Part 4)
"Threads are never useful in Python" They are the right tool for blocking libraries and I/O waits, and for GIL-releasing native calls (5.2)
"A C extension means no GIL problem" Only if its author released the lock. sorted, json.loads and re are C and hold it (2.4, 9.1)
"asyncio is affected by the GIL" A single-threaded loop never contends for it; the GIL costs asyncio nothing (1.4)
"Lowering the switch interval fixes everything" It lowers latency for Python-level work, at a throughput cost, and does nothing against one long native call (3.3)
"The GIL is why Python is slow" Single-thread speed is set by the interpreter; the GIL limits core count. The free-threaded build is about 5-10% slower single-threaded because replacing the lock costs something (atomics, per-object locks); parallel speed-up is what you buy with that cost
"Free-threaded Python is just a faster Python" It is a different trade: more parallelism for threaded CPU work, a modest single-thread and memory cost, and ecosystem risk (7.7)
"The GIL guarantees ordering between threads" It guarantees nothing about order; the OS decides which waiting thread runs next (2.2)
"More processes is always better" Memory multiplies and pickling costs add up; past the core count extra workers only add overhead (5.1)

Key takeaways#

  • The GIL is a lock in standard CPython that lets one thread at a time run Python bytecode. It exists because reference counting is not thread-safe without it, and it made built-ins and C extensions simple.
  • A thread waiting on I/O, a sleep or a lock releases the GIL; native code can release it too (Py_BEGIN_ALLOW_THREADS). That is why threads speed up waiting work and GIL-releasing native calls, and do nothing for pure-Python computation (Part 3).
  • The switch interval (default 5 ms) is a polite request, honoured between bytecodes. One long native call that holds the GIL stalls every other thread until it returns.
  • The convoy effect makes I/O threads pay a wait for the GIL on every wake-up when a CPU-bound thread is running. Keep CPU hogs out of latency-sensitive processes.
  • The GIL protects the interpreter's consistency, not your logic. Lock multi-step shared state (01C.3).
  • To use multiple cores: processes (proven, copy costs), native libraries that release the lock, subinterpreters (concurrent.interpreters, InterpreterPoolExecutor, 3.14+, extensions must opt in), or free-threaded CPython (PEP 703/779, supported but optional since 3.14, about 5-10% single-thread cost, extensions can re-enable the GIL).
  • Check what you run with sysconfig.get_config_var("Py_GIL_DISABLED") and sys._is_gil_enabled(); control it with PYTHON_GIL or -X gil.
  • Measure with the scaling harness, CPU time versus wall time, a heartbeat, and GIL-aware profilers, before choosing.
  • For an AI service: asyncio or threads for the waiting, processes or native libraries for the computing, and thread-safe code regardless of the build.

Where you'll use this in the AI path#

Where What you use from this lesson
01B.4 §8.1, the GIL in plain words and §8.6 The two-minute version you now understand in detail; why CPU-bound work needs processes
03.9 §4.8, threads for code that isn't async Blocking SDKs in a thread pool work because waiting releases the GIL (3.2)
03.9 §2.6, a sync call inside async code blocks everything The same stall mechanism as a GIL-holding native call (3.3)
05.2 §10.3, scale and robustness (PDF parsing) Why bulk parsing shards across processes (Part 10)
06.2 §2.5, batching for GPU throughput Batching amortises per-call overhead and lock traffic; native runtimes release the GIL
11C.1 §2.13, running it: uvicorn, gunicorn, workers Worker processes are the standard way to use several cores for a Python web service: each has its own GIL
01C.6, Python Memory Management Reference counting, the reason for the GIL, in full; why free-threading changes allocation
01C.7, Shared Memory and Inter-Process Communication The next step after processes: sharing data without pickling it

Terms introduced in this lesson#

Term Meaning
Global Interpreter Lock (GIL) the mutex in standard CPython that lets only one thread run Python bytecode at a time
Reference counting CPython's memory-management scheme: each object counts references to it and is freed at zero; the reason the GIL exists
Switch interval how long a waiting thread waits before asking the running thread to drop the GIL; sys.getswitchinterval(), 5 ms by default
Eval breaker the flag the interpreter loop checks at safe points to handle pending requests, including "drop the GIL"
Forced hand-off making a thread that dropped the GIL wait until another thread has taken it, so it cannot immediately re-grab it
Convoy effect I/O-bound threads repeatedly queuing for the GIL behind a CPU-bound thread, making their operations far slower than their own work
Py_BEGIN_ALLOW_THREADS the C-API macro pair that releases the GIL around native code that does not touch Python objects
GIL-bound a workload whose speed does not improve with more threads because it holds the GIL while it works
Subinterpreter an isolated Python interpreter inside one process, with its own modules and, optionally, its own GIL
concurrent.interpreters the 3.14 standard-library module (PEP 734) for creating and running subinterpreters
InterpreterPoolExecutor a concurrent.futures executor whose workers are threads each running in its own subinterpreter
Free-threaded build a CPython build with the GIL disabled (PEP 703); separate executable, often python3.14t
sys._is_gil_enabled() reports whether the GIL is on in the running process (3.13+)
PYTHON_GIL / -X gil the environment variable and flag that turn the GIL on or off in a free-threaded build
Biased reference counting the free-threaded build's scheme: an owner thread updates its count cheaply, other threads use an atomic one
Immortal object an object whose reference count is never updated (such as None; immortal objects arrived in 3.12 for all builds, PEP 683), so threads never contend over it
cp314t wheel a wheel built for the free-threaded 3.14 ABI
Scaling harness a script that runs the same function in 1 and N threads to measure whether it scales

Exercises#

All exercises use only the standard library. Solutions that are deterministic show real output from Python 3.14.6 (normal build).

Exercise 1: Which interpreter is this?#

Run the report script from 7.3 on your machine. State whether you have a free-threaded build and whether the GIL is on. Then predict what the same script prints after PYTHON_GIL=1.

Solution

Run python3 e07_gil_report.py. On a normal build the output is the first block in 7.3 (free-threaded build: False, GIL enabled right now: True). PYTHON_GIL=1 changes nothing on a normal build (the GIL is already on); on a free-threaded build it flips the second line to True. PYTHON_GIL=0 on a normal build is a fatal start-up error (7.4).

Exercise 2: Predict the reference counts#

Before running, predict the four numbers:

python
# ex02_refcount_predict.py: predict the counts before you run it.
import sys

doc = {"id": 1, "text": "refund request"}
print(sys.getrefcount(doc) - 1)       # 1: just the name `doc`

batch = []
for _ in range(3):
    batch.append(doc)                 # each append adds one reference
print(sys.getrefcount(doc) - 1)

batch.clear()
print(sys.getrefcount(doc) - 1)

def keep(d):
    return [d, d]                     # a list holding two references

held = keep(doc)
print(sys.getrefcount(doc) - 1)
Solution
Output · Python 3.14.64 lines
1
4
1
3

One name; the name plus three list slots; back to one after clear(); the name plus two slots in held. (getrefcount itself adds one temporary reference, hence the - 1.) The point: counts change on every assignment and every list append, which is why concurrent unprotected updates would corrupt them and why a global lock was the simplest safeguard.

Exercise 3: Predict the speed-up#

For each function, predict whether four threads on the default build give about x1, about x4, or something between, and why: (a) a loop summing squares in pure Python; (b) hashlib.sha256 over a 50 MB buffer; (c) time.sleep(1); (d) json.loads of a 20 MB string; (e) a requests.get to a slow server.

Solution

(a) about x1: pure bytecode holds the GIL. (b) near x4: hashlib releases the GIL for inputs above 2047 bytes. (c) x4: sleeping releases the lock. (d) about x1: json.loads is C but holds the GIL (the harness in 9.1 showed about x1). (e) near x4 while waiting: the network wait releases the lock (the parsing of the response afterwards does not). Confirm any of them with the harness.

Exercise 4: Count the cores in use#

Show with numbers that four sleeping threads use almost no CPU. (Contrast with the four busy threads of 3.1, which used 1.0 cores.)

Solution
python
# ex04b_sleeping_cores.py: four SLEEPING threads use almost no CPU: the GIL is not the limit here.
import threading
import time

wall0, cpu0 = time.perf_counter(), time.process_time()
threads = [threading.Thread(target=time.sleep, args=(0.3,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
wall, cpu = time.perf_counter() - wall0, time.process_time() - cpu0
print("wall time about 0.3 s, not 1.2 s:", 0.25 < wall < 0.6)
print("almost no CPU used (cpu/wall < 0.2):", cpu / wall < 0.2)
Output · Python 3.14.62 lines
wall time about 0.3 s, not 1.2 s: True
almost no CPU used (cpu/wall < 0.2): True

Four sleeps overlapped (0.3 s, not 1.2 s) and used almost no CPU: nothing to serialise.

Exercise 5: Why 536 milliseconds?#

In 3.3 the heartbeat was 536 ms late while the main thread ran sorted(BIG), even though the switch interval is 5 ms. Explain, and give three fixes for a web service that does this on a request thread.

Solution

A waiting thread can only request that the GIL be dropped; the running thread honours the request at its next eval-breaker check, between bytecodes. sorted(BIG) is one bytecode CALL into C code that does not release the lock, so no check happens until it returns: the whole sort is one uninterruptible slice. Fixes: (1) run the sort in a process (own GIL; shown by ex04_heartbeat_in_process.py in 3.3); (2) avoid the work (sort in the database, or keep data sorted at write time); (3) chunk the work so each piece is short and give other threads a chance between pieces, or use a library that releases the GIL for the heavy part. Lowering the switch interval would not help: the problem is not the slice length.

Exercise 6: Keep every outcome from a process pool#

A batch of documents includes an empty one that makes the parser raise ValueError. Write a process-pool run that prints a result or a failure for every document instead of crashing at the first error.

Solution
python
# ex06_pool_errors.py: an exception in a worker process is re-raised in the parent at result().
from concurrent.futures import ProcessPoolExecutor


def parse(doc: str) -> int:
    if not doc:
        raise ValueError("empty document")
    return len(doc.split())


if __name__ == "__main__":
    docs = ["refund request", "", "reset my password"]
    with ProcessPoolExecutor(max_workers=2) as pool:
        futures = [pool.submit(parse, d) for d in docs]   # submit, not map: keep every outcome
        for doc, fut in zip(docs, futures):
            try:
                print(repr(doc), "->", fut.result())
            except ValueError as exc:
                print(repr(doc), "-> failed:", exc)
Output · Python 3.14.63 lines
'refund request' -> 2
'' -> failed: empty document
'reset my password' -> 3

submit plus result() per future keeps each outcome separate; the exception was pickled in the worker and re-raised in the parent. With pool.map, iterating the results would raise at the failing item and hide the later ones (01B.4 §2.4 shows the result-type pattern).

Exercise 7: Prove two subinterpreters do not share modules#

Patch the json module in the main interpreter and again inside one subinterpreter, and show that each interpreter sees only its own patch. (Python 3.14+.)

Solution
python
# ex07_interp_isolation.py: modules are separate copies in each subinterpreter (3.14+).
import json
from concurrent import interpreters

json.marker = "set in the main interpreter"      # monkey-patch the main interpreter's json module

a = interpreters.create()
try:
    a.exec("import json; json.marker = 'set inside a'")
    print("main sees:", json.marker)
    print("a sees:   ", a.call(eval, "__import__('json').marker"))
finally:
    a.close()
Output · Python 3.14.62 lines
main sees: set in the main interpreter
a sees:    set inside a

Each interpreter has its own json module object, so the patch inside a never reached the main interpreter and vice versa. This is both the strength (no shared mutable state, no races) and the cost (every module is imported again per interpreter: slower start-up, more memory).

Exercise 8: A start-up guard#

Write a function require_gil_off() that raises RuntimeError unless the process is a free-threaded build with the GIL actually disabled, with a message that says which of the three situations you are in. Call it on your machine.

Solution

Reuse gil_status() from 7.4:

python
# ex08_require_gil_off.py: refuse to start if the GIL is on (for a service that needs free threading).
import sys
import sysconfig


def require_gil_off() -> None:
    if not hasattr(sys, "_is_gil_enabled"):
        raise RuntimeError("Python older than 3.13: the GIL is always on")
    if sys._is_gil_enabled():
        built_free = sysconfig.get_config_var("Py_GIL_DISABLED") == 1
        reason = "an extension or PYTHON_GIL=1 re-enabled it" if built_free else "this is a normal build"
        raise RuntimeError(f"the GIL is on: {reason}")


try:
    require_gil_off()
    print("GIL is off: threads run Python in parallel")
except RuntimeError as exc:
    print("refusing to start:", exc)
Output · Python 3.14.6, normal build1 line
refusing to start: the GIL is on: this is a normal build

Use this idea in a test or a health endpoint so a silently re-enabled GIL (7.4) is caught the day a dependency is upgraded.

Exercise 9: The convoy, predicted#

A service streams tokens to 200 clients from an asyncio loop on the main thread. Someone adds a background thread that counts tokens in pure Python for billing. Predict the symptom, say why, and give the fix.

Solution

Symptom: streams stutter and latency rises, even though CPU use looks moderate. Cause: the loop thread does many tiny steps, and each time it blocks in the selector or on a socket it releases the GIL and must ask for it back; the billing thread is a CPU hog, so the loop waits up to a switch interval (5 ms) each time (3.4). Fixes: move the counting to a process or a separate service; do it in batches off the request path; or, as a stop-gap, lower sys.setswitchinterval and measure. Check with a heartbeat or loop-lag monitor (9.2).

Exercise 10: Atomic or not?#

Under the GIL on the default build, which of these are safe from many threads without a lock, and which lose updates: (a) results.append(x); (b) count += 1 on a module global; (c) d[key] = value; (d) if key not in d: d[key] = compute(); (e) total = total + n?

Solution

(a) safe, (c) safe: single operations on a built-in (Part 4, 01C.3 §2.5). (b) and (e) are read-modify-write: they lose updates. (d) is check-then-act: compute() may run twice and both threads may write. "Safe" in (a) and (c) is a property of the default build documented in the FAQ; the free-threaded build aims for similar behaviour but recommends explicit locks. Use threading.Lock for (b), (d) and (e).

Exercise 11: Pick the model#

For each, choose threads, asyncio, a process pool, subinterpreters, or "native library" and justify in one line: (a) 500 embedding API calls; (b) hashing 10,000 uploaded files for dedupe; (c) extracting text from 3,000 PDFs with a pure-Python library; (d) cleaning and chunking text in pure Python on a 3.14 service whose dependencies are all pure Python; (e) a vector-similarity search over a NumPy matrix.

Solution

(a) asyncio with a bound: all waiting. (b) threads: hashlib releases the GIL on large inputs (typically about x3 to x4 in 9.1); processes also work but threads are cheaper. (c) process pool sharded by file: pure-Python bytecode is GIL-bound. (d) an InterpreterPoolExecutor is a candidate (pure-Python, compatible dependencies, 3.14+), with a process pool as the safe alternative; measure both (6.3). (e) a native library (NumPy), optionally with threads: large array operations release the GIL. Confirm the claims in (b) to (e) with the scaling harness.

Exercise 12: Change the build, change the result (needs a free-threaded build)#

If you have a free-threaded build (7.3), run e02_cpu_threads.py from 3.1 with python3.14t and compare the threads vs sequential figure with a normal build. Then take the unlocked count += 1 counter from 01C.3 and run it on both builds. Predict what changes. If you have no t build, uv run --python 3.14t (7.3) installs one without touching your system Python.

Solution

On the normal build the thread figure sits near x1 (threads share one GIL). On the free-threaded build it should move well above x1, towards the core count, because the threads really do run at the same instant (documentation-based prediction; the numbers are yours to measure). The unlocked counter is wrong on both builds in principle, but a GIL build can hide the race for long stretches because switches happen only at interval boundaries; free threading exposes it far more readily. The fix is the same on both: a threading.Lock.


Check yourself#

  1. In one sentence, what is the GIL?
  2. Why does CPython have a GIL? Name the mechanism that needs it.
  3. Does a thread blocked in socket.recv hold the GIL? What does that imply for I/O-bound threads?
  4. What is the switch interval, what is its default, and what does the documentation say about its precision?
  5. Why can one sorted() call on a huge list freeze every other thread for hundreds of milliseconds?
  6. What is the convoy effect, and which kind of thread suffers from it?
  7. What does the GIL protect, and what does it leave to you?
  8. Name three ways to use more than one core from Python, and one cost of each.
  9. What does InterpreterPoolExecutor do, in which Python version did it arrive, and what is the main practical limit?
  10. What did PEP 779 decide for Python 3.14, and what did it not decide?
  11. How do you tell whether a process is a free-threaded build, and whether its GIL is actually off?
  12. What happens when a free-threaded build imports a C extension that does not declare support?

Further resources#


← 01C.4: Deadlocks, Livelock and Starvation | Module 01C overview | 01C.6: Python Memory Management →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close