Python: concurrency, asyncio and the GIL

What one interpreter lock lets threads do, asyncio from the event loop up, and the two ways round the lock that ship today (the free-threaded build and subinterpreters), every example run on CPython 3.14.8, 3.14.8t and 3.15.0rc3 on an Apple M1 Pro. A child of Python: the essentials. Data as of October 2026. Reading: 19 min, plus 10 in closed details.

The idea in one screen

In the default CPython build one lock, the GIL, lets only one thread run Python bytecode at a time, so threads overlap waiting but never computing. asyncio replaces many waiting threads with one event loop that switches tasks only at an await, so a single blocking call stalls every task. To compute in parallel you need several GILs (processes, subinterpreters), no GIL (the free-threaded build), or native code that releases it.

Fig. 1 shows who runs Python bytecode on four CPU cores in each of the six arrangements this page measures; the numbers are this page's runs on CPython 3.14.8 and 3.14.8t (an Apple M1 Pro, 2026-10-05).

  1. Four threads, one GIL. All four threads belong to one interpreter (the glass plate), and only the thread holding the GIL (the gold token) runs bytecode; the others are ready but wait. The token hops between them: sys.getswitchinterval() read 5 ms in the recorded runs. So the CPU job took 0.96 s serially and 0.99 s on four threads.
  2. Waiting gives the GIL back. A thread inside time.sleep, a socket read or a file read releases the lock while the operating system does the waiting, so four waits overlap: four 200 ms waits took 0.83 s one after another and 208 ms on four threads.
  3. Four processes, four GILs. Each worker process has its own interpreter and its own lock, so all four compute at once. Arguments and results cross between processes as pickles (the orange dots). The CPU job took 0.36 s; spawning one process cost 84.4 ms on 3.14.8 (section 4).
  4. Four subinterpreters, four GILs, one process. Since 3.12 each subinterpreter has its own GIL, so they compute in parallel inside one process, still passing pickles. One started in 5.985 ms, against 84.4 ms for a spawned process and 0.052 ms for a thread (section 4).
  5. The free-threaded build: no GIL. python3.14t has one interpreter and no token: all four threads run bytecode at the same moment, and the CPU job fell from 0.94 s serially to 0.37 s on four threads.
  6. asyncio: one thread, many waits. One thread runs one task at a time; the others are suspended at an await while the operating system waits for them. A task gives up the thread only at an await. Fig. 3 replays a real loop event by event.

You need: Python: the essentials (names, objects and the one interpreter). What a thread, a lock and epoll are at the operating-system level, and the GIL seen as an OS lock, is Concurrency: threads, locks, futexes, deadlock, and event-driven I/O (sections 1, 7 and 8); this page is what the lock means in Python code, with measurements.

GIL
the global interpreter lock: only the thread holding it runs Python bytecode.
Free-threaded build
CPython compiled without the GIL (python3.14t), installed separately.
Coroutine
what calling an async def function returns: a paused computation that runs only when awaited or wrapped in a task.
Task
a coroutine scheduled on the event loop, so it runs concurrently with other tasks.
Event loop
one thread that runs ready tasks until each reaches an await, and wakes them when what they wait for happens.
Cooperative
a task gives up the thread only at an await; nothing interrupts it.
Subinterpreter
a second, isolated interpreter in the same process, with its own GIL.
CPU-bound, I/O-bound
limited by computing, or by waiting (network, disk, a model API).

1. Threads, the GIL and processes

CPython's default build has a global interpreter lock (GIL): "the mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time" (glossary). Threads are real operating-system threads, but only the one holding the GIL runs Python code. A thread releases it while it waits for I/O or sleeps, and C extensions such as NumPy release it during long computations. So threads give concurrency for waiting, not parallelism for Python computing. Processes each have their own interpreter and their own GIL, so they compute in parallel, at the cost of start-up time and of pickling (serialising) every argument and result between processes.

How the lock is handed between threads, and what the free-threaded build replaces it with inside, is the OS view on Concurrency, section 7. How a worker process is created (fork, forkserver or spawn, and why 3.14 changed the Linux default) is Processes and the system-call API, section 9.

The experiment: the same CPU job (count primes below 250,000 by trial division, four times) and the same I/O job (four 200 ms waits), each run serially, on four threads and on four processes, best of three, pool start-up inside the timing as in a real script.

Four threads did the CPU job no faster than one (0.96 s serial, 0.99 s on four threads): exactly the GIL. Four processes did it about 2.7 times faster, not four, because starting the pool and moving data between processes is inside the timing and the laptop was busy (load average near 8 on 10 cores). For waiting, threads are as good as anything: four 200 ms waits took 208 ms.

Python 3.14's free-threaded build (python3.14t, officially supported since 3.14, PEP 779) has no GIL. On the same file its four threads compute in parallel (0.94 s to 0.37 s). The price: code that was accidentally safe under the GIL is not any more, and C extensions must declare support; section 3 measures both.

The script, k1_gil.py, and its two real outputs (code)
k1_gil.py
"""The same CPU-bound job and the same I/O-bound job, run serially, on 4 threads and on 4 processes.
Wall-clock seconds, best of 3. CPU job: count primes below 250,000 by trial division, 4 times.
Pool start-up is inside the timing, as it is in a real script."""
import os, sys, sysconfig, time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def count_primes(limit):                 # pure-Python CPU work: holds the GIL while it runs
    n = 0
    for k in range(2, limit):
        for d in range(2, int(k ** 0.5) + 1):
            if k % d == 0:
                break
        else:
            n += 1
    return n

def wait_io(_):                          # stands in for a network call: sleeping releases the GIL
    time.sleep(0.2)
    return 1

def pool(kind, fn, args):
    with kind(max_workers=4) as ex:
        return list(ex.map(fn, args))

def best(f, reps=3):
    ts = []
    for _ in range(reps):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts)

if __name__ == "__main__":
    gil = "free-threaded" if sysconfig.get_config_var("Py_GIL_DISABLED") else "GIL"
    print(f"Python {sys.version.split()[0]} ({gil} build), {os.cpu_count()} CPUs, load {os.getloadavg()[0]:.2f}")
    jobs = [250_000] * 4
    for name, f in [("CPU serial", lambda: [count_primes(j) for j in jobs]),
                    ("CPU 4 threads", lambda: pool(ThreadPoolExecutor, count_primes, jobs)),
                    ("CPU 4 processes", lambda: pool(ProcessPoolExecutor, count_primes, jobs)),
                    ("I/O serial", lambda: [wait_io(i) for i in range(4)]),
                    ("I/O 4 threads", lambda: pool(ThreadPoolExecutor, wait_io, range(4)))]:
        print(f"{name:16} {best(f):6.3f} s")
real output, Python 3.14.8
Python 3.14.8 (GIL build), 10 CPUs, load 7.96
CPU serial        0.957 s
CPU 4 threads     0.988 s
CPU 4 processes   0.357 s
I/O serial        0.826 s
I/O 4 threads     0.208 s
the same file, real output, Python 3.14.8 free-threaded build
Python 3.14.8 (free-threaded build), 10 CPUs, load 7.88
CPU serial        0.939 s
CPU 4 threads     0.369 s
CPU 4 processes   0.311 s
I/O serial        0.833 s
I/O 4 threads     0.208 s

Fig. 2 · Four threads compute no faster than one, unless the GIL is gone

2. asyncio from the event loop up

An event loop is a loop on one thread that keeps a queue of tasks ready to run and a list of things being waited for (sockets, timers). It runs a ready task until that task says "I am waiting for X", then runs the next ready task; when X happens, the waiting task goes back on the ready queue. Nothing is interrupted: a task gives up the thread only at an await. That is cooperative multitasking. Underneath, the loop asks the operating system which sockets are ready with one call (epoll on Linux, kqueue on macOS), which Concurrency section 8 explains.

The pieces: async def defines a coroutine function; calling it runs nothing and returns a coroutine object, a paused computation. await c runs c until it finishes, suspending the current coroutine whenever c waits. A task (asyncio.create_task(c)) wraps a coroutine and schedules it on the loop to run concurrently with the others. asyncio.run(main()) creates a loop, runs main to completion and closes the loop. Two predictions first:

a1_coro.py
import asyncio, inspect

async def fetch(name):
    print(f"fetch({name}) starts")
    await asyncio.sleep(0.01)
    return name.upper()

c = fetch("a")                      # nothing runs yet: calling makes a coroutine OBJECT
print(type(c).__name__, inspect.getcoroutinestate(c))
print(asyncio.run(c))               # the event loop drives it to completion

fetch("b")                          # created and never awaited: it never runs
import gc; gc.collect()             # CPython warns when the unused coroutine is destroyed
print("end")
Predict the output, then reveal
real output, Python 3.14.8
coroutine CORO_CREATED
fetch(a) starts
A
a1_coro.py:12: RuntimeWarning: coroutine 'fetch' was never awaited
  fetch("b")                          # created and never awaited: it never runs
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
end
gather keeps argument order
import asyncio
async def f(n):
    await asyncio.sleep(n / 100)
    print('done', n)
    return n
async def main():
    print(await asyncio.gather(f(3), f(1), f(2)))
asyncio.run(main())
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
done 1
done 2
done 3
[3, 1, 2]

The second answer: tasks finish in the order their waits end (1, 2, 3), but gather returns results in the order of its arguments, [3, 1, 2].

Three coroutines, four ways

Three coroutines wait 100, 200 and 300 ms. Awaited one after another they take 0.6 s; started together with asyncio.gather they take 0.3 s, the longest single wait. Then the middle one calls blocking time.sleep(0.2) instead of await asyncio.sleep(0.2). Every step of Fig. 3 is a stretch of real events from a2_trace.py, stamped with the loop's clock; the ruler at the front is that clock, 0 to 620 ms for all four modes, so they compare by eye. A task sits in the ready queue (left), on the one thread (centre), suspended at an await on the loop's timers (back), or done (right).

  1. A starts and suspends (0.2 ms). main awaits A directly, so A runs on the thread until await asyncio.sleep(0.1), then parks on a timer due at 100 ms. B and C do not exist yet: await in a loop creates each coroutine only when the one before it has finished.
  2. A resumes and finishes (100.6 ms). The timer fires, the loop puts A back on the thread, and A returns its result.
  3. B starts and suspends (100.6 ms). Only now does main create B, which waits 200 ms.
  4. B finishes (302.8 ms). For 200 ms the thread had nothing to do.
  5. C starts and suspends (302.8 ms). 300 ms more.
  6. C finishes (604.9 ms): total 605.2 ms. The three waits ran back to back, 100 + 200 + 300 ms: await in a loop is sequential.
The script, a2_trace.py, and its real output (code)
a2_trace.py
"""Three coroutines, four ways of running them. Every event is stamped with the event
loop's clock (ms since the run started); the event-loop stepper on this page replays these traces."""
import asyncio, json, sys, time

EV = []
def ev(who, what, note=""):
    EV.append([who, what, round((time.perf_counter() - T0) * 1000, 1), note])

async def fetch(name, secs):
    ev(name, "start")
    ev(name, "await", f"asyncio.sleep({secs})")
    await asyncio.sleep(secs)                  # suspends: control goes back to the loop
    ev(name, "resume")
    ev(name, "done")
    return name

async def fetch_blocking(name, secs):
    ev(name, "start")
    ev(name, "block", f"time.sleep({secs})")
    time.sleep(secs)                           # blocks the whole thread: no other coroutine can run
    ev(name, "done")
    return name

async def fetch_thread(name, secs):
    ev(name, "start")
    ev(name, "await", f"asyncio.to_thread(time.sleep, {secs})")
    await asyncio.to_thread(time.sleep, secs)  # the blocking call runs in a worker thread
    ev(name, "resume")
    ev(name, "done")
    return name

JOBS = [("A", 0.10), ("B", 0.20), ("C", 0.30)]

async def sequential():
    return [await fetch(n, s) for n, s in JOBS]

async def gathered():
    return await asyncio.gather(*(fetch(n, s) for n, s in JOBS))

async def gathered_blocking():
    return await asyncio.gather(fetch("A", 0.10), fetch_blocking("B", 0.20), fetch("C", 0.30))

async def gathered_thread():
    return await asyncio.gather(fetch("A", 0.10), fetch_thread("B", 0.20), fetch("C", 0.30))

out = {}
for mode in (sequential, gathered, gathered_blocking, gathered_thread):
    EV.clear()
    T0 = time.perf_counter()
    res = asyncio.run(mode())
    total = round((time.perf_counter() - T0) * 1000, 1)
    out[mode.__name__] = {"events": list(EV), "total_ms": total, "result": res}
    print(f"{mode.__name__:18} {total:6.1f} ms  order of events: " +
          " ".join(f"{w}:{e}" for w, e, _, _ in EV))
with open(sys.argv[1] if len(sys.argv) > 1 else "/dev/null", "w") as f:
    json.dump(out, f)
real output, Python 3.14.8
sequential          605.2 ms  order of events: A:start A:await A:resume A:done B:start B:await B:resume B:done C:start C:await C:resume C:done
gathered            302.5 ms  order of events: A:start A:await B:start B:await C:start C:await A:resume A:done B:resume B:done C:resume C:done
gathered_blocking   505.0 ms  order of events: A:start A:await B:start B:block B:done C:start C:await A:resume A:done C:resume C:done
gathered_thread     305.7 ms  order of events: A:start A:await B:start B:await C:start C:await A:resume A:done B:resume B:done C:resume C:done
Never block the loop
"If a function performs a CPU-intensive calculation for 1 second, all concurrent asyncio Tasks and IO operations would be delayed by 1 second" (Developing with asyncio). Culprits: requests, time.sleep, a synchronous database driver, a big json.loads, tokenising a long document. Fixes: an async library, await asyncio.to_thread(f), or a process pool via loop.run_in_executor. Debug mode reports any step that holds the loop longer than 100 ms:
a6_debug.py
import asyncio, time

async def handler():
    time.sleep(0.2)                    # a blocking call hiding in async code
    await asyncio.sleep(0)

asyncio.run(handler(), debug=True)     # or PYTHONASYNCIODEBUG=1, or python -X dev
real output, Python 3.14.8
Executing <Task pending name='Task-1' coro=<handler() running at a6_debug.py:5> cb=[_run_until_complete_cb() at <stdlib>/asyncio/base_events.py:181] created at <stdlib>/asyncio/runners.py:110> took 0.210 seconds

A real HTTP fan-out against a local server

The common LLM-application pattern: call an API many times concurrently, but not unboundedly. A standard-library server (asyncio.start_server) answers GET /delay/100 after 100 ms, standing in for a model API; the client opens a connection per request with asyncio.open_connection. Twenty calls, timed in Fig. 4:

Twenty sequential calls take twenty times 100 ms. gather overlaps all the waits: 0.10 s. A Semaphore(5) keeps at most five requests in flight (rate limits are real), giving four waves of 100 ms. TaskGroup (3.11+) is gather with structured clean-up: if one task fails, the others are cancelled and the errors arrive together as an ExceptionGroup. asyncio.timeout (3.11+) bounds a block of awaits: one 2 s call with a 250 ms budget stopped at 0.252 s.

The script, a3_fanout.py (server and client, standard library only), and its real output (code)
a3_fanout.py
"""A real HTTP fan-out against a local server, standard library only.
The server answers GET /delay/<ms> after <ms> milliseconds (like a slow model API).
The client opens a TCP connection per request with asyncio.open_connection."""
import asyncio, time

async def handle(reader, writer):              # one coroutine per incoming connection
    request_line = (await reader.readline()).decode()
    while (await reader.readline()) not in (b"\r\n", b""):
        pass                                   # skip headers
    ms = int(request_line.split()[1].rsplit("/", 1)[1])
    await asyncio.sleep(ms / 1000)
    body = f"slept {ms} ms".encode()
    writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s" % (len(body), body))
    await writer.drain()
    writer.close()

async def get(port, path):
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    writer.write(f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".encode())
    await writer.drain()
    raw = await reader.read()                  # read until the server closes
    writer.close()
    await writer.wait_closed()
    return raw.split(b"\r\n\r\n", 1)[1].decode()

async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    delays = [100] * 20                        # 20 calls of 100 ms each

    t0 = time.perf_counter()
    for d in delays:
        await get(port, f"/delay/{d}")         # one after another
    print(f"sequential, 20 calls      {time.perf_counter() - t0:6.3f} s")

    t0 = time.perf_counter()
    bodies = await asyncio.gather(*(get(port, f"/delay/{d}") for d in delays))
    print(f"gather, 20 at once        {time.perf_counter() - t0:6.3f} s   {bodies[0]!r}")

    limit = asyncio.Semaphore(5)               # at most 5 in flight: be polite to the API
    async def polite(d):
        async with limit:
            return await get(port, f"/delay/{d}")
    t0 = time.perf_counter()
    await asyncio.gather(*(polite(d) for d in delays))
    print(f"gather, at most 5 at once {time.perf_counter() - t0:6.3f} s")

    t0 = time.perf_counter()
    async with asyncio.TaskGroup() as tg:      # 3.11+: same speed, and cancels siblings on failure
        tasks = [tg.create_task(get(port, f"/delay/{d}")) for d in delays]
    print(f"TaskGroup, 20 at once     {time.perf_counter() - t0:6.3f} s   {len(tasks)} results")

    t0 = time.perf_counter()
    try:
        async with asyncio.timeout(0.25):      # one slow call (2 s) with a 250 ms budget
            await get(port, "/delay/2000")
    except TimeoutError:
        print(f"timeout after             {time.perf_counter() - t0:6.3f} s")

    server.close()
    await server.wait_closed()

asyncio.run(main())
real output, Python 3.14.8
sequential, 20 calls       2.058 s
gather, 20 at once         0.104 s   'slept 100 ms'
gather, at most 5 at once  0.416 s
TaskGroup, 20 at once      0.107 s   20 results
timeout after              0.252 s

Fig. 4 · Twenty 100 ms calls: overlapped, they take one call's time

Cancellation and timeouts

task.cancel() does not stop a task immediately; it arranges for CancelledError to be raised inside it at its current await, so its finally blocks and async with exits run. A timeout is a cancellation that the timeout block turns into TimeoutError. The rule: if you catch CancelledError to clean up, re-raise it. A coroutine that swallows it reports success to whoever cancelled it, and TaskGroup and timeout stop working around it. The real run: w1 re-raises, the swallower returns a value, w2 sits under a 50 ms timeout.

real output of a4_cancel.py, Python 3.14.8
w1: working
w1: cancelled, cleaning up
w1: finally
main: w1 is cancelled: True
swallower: caught CancelledError and returned (a bug)
main: swallower result: pretends to have finished | cancelled(): False
w2: working
w2: cancelled, cleaning up
w2: finally
main: w2 timed out
The script, a4_cancel.py (code)
a4_cancel.py
import asyncio

async def worker(name):
    try:
        print(f"{name}: working")
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print(f"{name}: cancelled, cleaning up")
        raise                                   # always re-raise CancelledError
    finally:
        print(f"{name}: finally")

async def swallower():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("swallower: caught CancelledError and returned (a bug)")
        return "pretends to have finished"

async def main():
    t = asyncio.create_task(worker("w1"))
    await asyncio.sleep(0.01)                   # let it start
    t.cancel()                                  # request: CancelledError is raised at its await
    try:
        await t
    except asyncio.CancelledError:
        print("main: w1 is cancelled:", t.cancelled())

    s = asyncio.create_task(swallower())
    await asyncio.sleep(0.01)
    s.cancel()
    print("main: swallower result:", await s, "| cancelled():", s.cancelled())

    try:
        async with asyncio.timeout(0.05):       # a timeout is a cancellation plus a TimeoutError
            await worker("w2")
    except TimeoutError:
        print("main: w2 timed out")

asyncio.run(main())

Async generators: streaming responses

An async def containing yield is an async generator (PEP 525), consumed with async for. It is exactly how the async LLM SDKs expose a streamed response: each step awaits the next chunk, so other tasks keep running between tokens (in the run below, a ticker task ran 7 times meanwhile). Close it with aclose() when you stop early, so its clean-up runs now and not whenever the garbage collector gets to it.

The script, a5_stream.py, and its real output (code)
a5_stream.py
"""Async generators: how LLM SDKs stream tokens. The consumer uses `async for`."""
import asyncio, time

async def stream_tokens(text, delay=0.02):
    try:
        for tok in text.split(" "):
            await asyncio.sleep(delay)          # waiting for the next chunk from the network
            yield tok + " "
    finally:
        print("\n[stream closed]")

async def ticker(stop):
    n = 0
    while not stop.is_set():
        await asyncio.sleep(0.02)
        n += 1
    return n

async def main():
    stop = asyncio.Event()
    tick = asyncio.create_task(ticker(stop))    # other work keeps running while we stream
    t0 = time.perf_counter()
    async for tok in stream_tokens("the event loop interleaves waiting, never computing"):
        print(tok, end="", flush=True)
    stop.set()
    print(f"streamed in {time.perf_counter() - t0:.2f} s; the ticker ran {await tick} times meanwhile")

    agen = stream_tokens("stop me after two tokens please")
    got = []
    async for tok in agen:
        got.append(tok)
        if len(got) == 2:
            break                               # leaves the generator suspended
    await agen.aclose()                         # run the generator's finally now, not at GC
    print("got", got)

asyncio.run(main())
real output, Python 3.14.8
the event loop interleaves waiting, never computing 
[stream closed]
streamed in 0.15 s; the ticker ran 7 times meanwhile

[stream closed]
got ['stop ', 'me ']

Python 3.14 adds python -m asyncio ps PID and pstree PID to list the tasks of a running process (What's new in 3.14). JavaScript has the same single-threaded loop built into every runtime (JavaScript: the event loop, promises and streams); Rust's async with tokio is Rust: async with tokio, services with axum, and CLIs. Choosing async, threads or worker processes inside a web service is Building a backend API.

3. Free-threading in practice

The free-threaded build removes the GIL (PEP 703): experimental in 3.13, officially supported but still optional in 3.14 (PEP 779), installed separately as python3.14t (uv python install 3.14t). Check which one you are on with sys._is_gil_enabled().

Fig. 5 · With the GIL four lanes do one core's work; without it they run at once

The workload is the parent topic's program: count tokens per user over 100,000 JSONL chat lines (the root's generator, seed 7), split across threads, each thread filling its own Counter that the main thread merges (src/pb/ft/). Every thread recorded when it finished each block of 1,000 lines; Fig. 5 is that recording, to scale, for four threads on four interpreters, one step each, on one time axis. A dark block is finished, a pale one in progress. Predict before step 2: with the GIL, do four threads finish sooner than one?

  1. 3.14.8, with the GIL: 648 ms. All four lanes move, but slowly: each block of 1,000 lines took 3.9 times as long as one thread alone needs for it, because the threads take turns holding the GIL. One thread alone took 633 ms (median of the scaling runs), so four threads were 1.0x as fast: four lanes, one core's worth of work.
  2. 3.14.8t, no GIL: 330 ms. The four threads run at the same moment on different cores. A block took 1.8 times as long as alone (1 would be perfect parallelism; the excess is the busy machine and contention). One thread took 683 ms, so four were 2.1x faster. The 3.14 finish stays marked on the axis.
  3. 3.15.0rc3, with the GIL: 752 ms. The same picture as 3.14: blocks 4.2 times as long as alone, one thread 686 ms, so 0.9x.
  4. 3.15.0rc3t, no GIL: 334 ms. Blocks 1.5 times as long as alone; one thread took 830 ms, so 2.5x. Both free-threaded builds finish in about half the time of both GIL builds.

Speed-up over one thread on the same interpreter, median of five runs. Section 1 timed a different CPU-bound job on 3.14t (0.94 s serial, 0.37 s on four threads, about 2.5x); this final run of the token counter measured with four threads, under a heavier load. Both are rough: on a busy laptop the same job varies by tens of percent between runs.

Every scaling run, 1 to 8 threads, and the single-thread overhead (all runs)

100,000 lines split evenly across N threads; each thread counts into its own Counter, then the main thread merges and checks the total against a single-threaded run. Five timed runs per point after one warm-up; the chart shows the median, the table every run. Script: src/pb/ft/ft_bench.py. One laptop (Apple M1 Pro: 8 performance and 2 efficiency cores, 16 GB, macOS 27) in normal use: treat differences under about 10% as noise; ratios on the same interpreter are more portable than absolute times.

Fig. 6 · Speed-up over one thread: only the free-threaded builds scale

The bug the GIL was hiding (and was not preventing)

Now the same four threads update one shared dictionary instead of their own: shared[user] = shared.get(user, 0) + n. That line reads, adds and writes back in three steps; if two threads read the same old value, one addition is lost.

Python's documentation never promised that a read-modify-write like this is atomic under the GIL (Python FAQ); the GIL only made losing an update rare. Without the GIL the same bug happens on most runs (the parent topic's section 9, Concurrency, measured about 70% of unsynchronised counter updates lost, Topic: programming-languages). What the free-threaded build does guarantee is that built-in objects stay internally consistent: the dictionary never crashes or corrupts, it only holds the wrong totals. The fixes are the same on both builds: a threading.Lock around the update (exact in every run), or, better, no shared state, which is what the scaling run did. How an update is lost instruction by instruction, and what a mutex or an atomic changes, is drawn on Concurrency, section 2.

Will your dependencies run without the GIL?

A C, C++ or Rust extension must declare that it is safe without the GIL. If it does not, importing it on the free-threaded build silently turns the GIL back on for the whole process, with a warning. Real output from two tiny C extensions, identical except for one line that declares support (Py_mod_gil):

-X gil=0 (or PYTHON_GIL=0) forces it off anyway, at your own risk. Packages that have not been ported may also refuse to build. This is orjson 3.12.0, which has no free-threaded wheel, being built from source for 3.14t:

Real output of uv run --python 3.14t --with orjson==3.12.0 on 2026-10-05, filtered to the error lines (paths shortened to ...); the full log is long.

Which popular compiled packages ship free-threaded wheels (the survey)

A missing cp314t wheel means an installer on 3.14t builds from the sdist (which needs a compiler, and may refuse, as orjson does) or fails. abi3 wheels do not load on free-threaded builds; abi3t (3.15+) does; wheel tags are Python: typing, uv, packaging and the toolchain. polars appears as polars-runtime-32 because the polars wheel itself is now pure Python. Script: src/pb/pack/wheels.py.

What it costs, and when not to use it
  • Single-thread speed. The 3.13 HOWTO measured about 40% overhead; for 3.14, What's New says "roughly 5-10%" and the 3.14 HOWTO "about 1% on macOS aarch64 to 8% on x86-64 Linux" (pyperformance). Measured here on one workload: .
  • Memory. PEP 779 set a 20% memory overhead target for phase II; this page did not measure memory.
  • Your own thread safety. Races that the GIL made rare now happen; audit shared mutable state before switching.
  • Dependencies. One unported extension turns the GIL back on for everyone (above).
  • Not for I/O-bound work: threads already overlap waiting under the GIL, and asyncio is the usual tool for many connections.
Whether the free-threaded build ever becomes the default ("phase III") is "left for a future PEP" (PEP 779); the old page's forecast of 3.16 to 3.17 is a guess, not a plan.
Corrections to the old Notion page (provenance)
  • "~3x speedups on 4-core CPU-bound thread pools": no source given. Measured here on a busy 10-core laptop: with 4 threads on 3.14t.
  • "single-digit-percent single-thread overhead (down from ~40% in 3.13)": both figures are the official ones (3.14 What's New, 3.13 HOWTO); this workload measured .
  • "free-threaded builds (3.14+)": imprecise. The free-threaded build was experimental from 3.13 (PEP 703) and officially supported from 3.14 (PEP 779).

4. Subinterpreters (3.14), measured

A subinterpreter is a second, isolated Python interpreter inside the same process: its own modules, its own globals and, since 3.12, its own GIL (PEP 684). 3.14 exposed them in the standard library (PEP 734): concurrent.interpreters and InterpreterPoolExecutor, which has the same interface as the thread and process pools. They sit between threads and processes: parallel on the normal GIL build like processes, but cheaper to start, and like processes they share nothing by default: arguments and results cross by pickling, except immutable built-ins (None, bool, bytes, str, int, float and tuples of these), which are shared or copied cheaply, and memoryview and interpreter queues, which really share mutable data (docs).

from concurrent.futures import InterpreterPoolExecutor with InterpreterPoolExecutor(max_workers=4) as ex: totals = list(ex.map(count_slice, parts)) # same code as with ThreadPoolExecutor

On this job, subinterpreters and processes both clearly beat threads on the GIL build, because each worker has its own GIL; processes were somewhat faster here. Neither reached 4x with 4 workers: each worker receives 25,000 lines by pickling and returns a pickled Counter, and the machine was busy. A new subinterpreter started more than ten times faster than a spawned process, and about a hundred times slower than a thread.

Every run, with the method and the machine's load (all runs)

Start-up: create a worker and run a trivial function in it (median of 20 for threads and subinterpreters, 10 for spawned processes). Job: the 100,000-line count split 4 ways with each executor, median of 5 (the result is checked every time). Script: src/pb/interp/interp_bench.py.

Fig. 7 · Each worker with its own GIL: processes and subinterpreters beat threads

The mistake everyone makes first: a subinterpreter has its own sys.path, so a module the main interpreter found through a sys.path.insert is invisible to it. Simple arguments can hide this; a list argument has to be pickled together with the function, and then it fails:

What it costs, and when not to use it
Every extension module must opt in to being loaded in several interpreters, and the most important one has not:
Objects cannot be shared, only copied; and on the free-threaded build plain threads already run in parallel with shared memory. Use them on the normal build for CPU-bound work whose inputs and outputs are small, when process start-up is the problem.

5. Choosing

Your work isUseWhy, and the cost
Waiting on many network calls, with async libraries (httpx, an async SDK)asyncioThousands of waits on one thread, tiny memory per task; everything must be async, and one blocking call stalls all of it (section 2)
Waiting, with blocking libraries (requests, a database driver, boto3)ThreadPoolExecutorWorks with any library; each thread costs a stack and the GIL hand-offs; shared state needs locks
Computing in Python, normal buildProcessPoolExecutor, or InterpreterPoolExecutor when start-up mattersTrue parallelism, each worker with its own GIL; start-up, pickling, memory per worker (sections 1 and 4)
Computing in Python, dependencies all portedthreads on the free-threaded buildShared memory, no pickling; single-thread overhead, and your own races now bite (section 3)
Computing on arraysNumPy, PyTorch, a Rust or C++ extensionThe loop runs in native code, often releasing the GIL (Python: CPython internals and performance; Rust: speeding up Python with PyO3 and maturin)

Two beliefs the measurements correct:

  • "The GIL made x += 1 safe." It made races rare, not impossible: the GIL build lost updates in section 3's measurement too. Use a lock or per-thread state.
  • "Switch to the free-threaded build to speed up I/O-bound code." Threads already overlap waits under the GIL. The free-threaded build helps only CPU-bound Python running in several threads, and costs single-thread speed and dependency risk.

The GIL as a capacity question for a server (how many workers, pool sizes, py-spy on a live service) is Capacity planning and performance, which measured the GIL against free-threaded Python on a server workload.

Built 2026-10-26 by splitting the Python language page (its Part 1 sections 9 and 10, Event loop tab, Part 2 sections 9 and 11 and Runtime lab parts 1, 2, 4 and 5); every output is the recorded run from that page, made on 2026-10-05 on an Apple M1 Pro in normal use (src/README.md says how). What transfers to a Linux server: which model wins and the shape of each result; what does not: absolute times, and speed-ups on a machine whose other cores were busy.