Sub topic 14
Where the GIL is going: free-threaded builds and per-interpreter GIL
This chapter assumes you have read the earlier chapters on threads, processes, and the GIL. You should know that the GIL lets only one thread run Python bytecode at a time, that it makes CPU-bound threads no faster, and that locks are still needed for compound operations on shared state.
The GIL is changing, but slowly and with opt-in steps. Two separate efforts exist. They solve different problems, and they are often confused. This chapter describes both at the level that is stable, and it tells you which details to check against your own Python version.
Two different answers to one problem
The GIL exists because CPython's memory management (reference counting) and many internal structures are not safe for several threads to modify at once. There are two ways to avoid a single global lock:
- Remove the lock and make the interpreter's internals thread-safe. This is the free-threaded build (PEP 703). Many threads share one interpreter and its objects, and they run in parallel.
- Keep a lock but give each interpreter its own. This is the per-interpreter GIL (PEP 684). Several isolated interpreters live in one process. Each has its own GIL, so they run in parallel, but they do not share Python objects.
| Aspect | Free-threaded build | Per-interpreter GIL |
|---|---|---|
| Parallelism unit | Threads in one interpreter | Separate interpreters in one process |
| Shared Python objects | Yes, same as ordinary threads | No, data is copied or passed through channels |
| Needs a special Python build | Yes (`python3.13t`, or the free-threaded variant of later releases) | No, part of the standard build |
| Extension modules | Must be adapted or the GIL comes back | Must support multiple interpreters |
| Main risk | Data races in code that relied on the GIL | Isolation limits what you can share |
The status timeline
The details below are the ones that have been stable across releases. Check the "What's New" page for your Python version before relying on anything newer.
Two points follow from this:
- In 3.12 the per-interpreter GIL existed, but only C code could create interpreters with their own GIL. Ordinary Python programs could not use it.
- The free-threaded build is a separate build, not a runtime switch on the standard one. Standard builds from python.org and most Linux distributions still have the GIL. Installers and distributions usually offer the free-threaded build as a separate download or package.
The free-threaded build
In a free-threaded build, two threads running pure-Python CPU-bound code can use two cores at once. The CPU-bound threading experiment from the earlier chapters, where threads were no faster than one thread, can then show a real speedup.
Making this safe required changes inside the interpreter. Without depending on exact details, the main ideas are:
- Reference counting is adapted so that objects used by one thread do not need atomic updates on every access.
- Some objects, such as small integers and interned strings, are immortal and never need counting.
- Built-in containers such as
listanddictuse fine-grained internal locks, so concurrent use does not corrupt them.
The cost is that a free-threaded build can be slower on single-threaded code than a standard build. The gap has narrowed from release to release, so measure on your own version and workload instead of trusting a number from an article.
Detecting which build you have
Two checks are useful. sysconfig tells you how the interpreter was built. sys._is_gil_enabled() tells you whether the GIL is active right now.
import sys
import sysconfig
built_free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
# sys._is_gil_enabled() exists in Python 3.13 and later; older versions always have a GIL.
gil_enabled = getattr(sys, "_is_gil_enabled", lambda: True)()
print("Version:", sys.version.split()[0])
print("Built free-threaded:", built_free_threaded)
print("GIL enabled now:", gil_enabled)On a standard build, the output says Built free-threaded: False and GIL enabled now: True. On a free-threaded build, the second line is normally True for "built" and False for "GIL enabled".
The GIL can come back at runtime
A free-threaded build can still run with the GIL enabled. There are two reasons:
- You asked for it. The environment variable
PYTHON_GIL=1or the option-X gil=1turns the GIL on.PYTHON_GIL=0or-X gil=0turns it off. - You imported a C extension that has not declared that it is safe without the GIL. The interpreter then re-enables the GIL for the whole process and emits a warning.
The second case is the common surprise. A single old extension in a dependency tree can quietly remove all parallelism. That is why sys._is_gil_enabled() is checked at runtime, after all imports, and not assumed from the build.
Free-threading does not remove the need for locks
The GIL hid many bugs. Code like counter += 1 was never atomic even with the GIL, but with a GIL the unlucky interleavings were rare, so broken code often seemed to work. Without a GIL, threads truly run at the same time, and those bugs show up more often.
The earlier locked counter example is still correct and still necessary. The built-in containers will not crash or corrupt their internal state when used from several threads, but a sequence such as "check whether a key exists, then insert it" is still not atomic. Protect compound operations with a threading.Lock, or use queue.Queue to hand work between threads.
The per-interpreter GIL
A CPython process can hold several interpreters. Each has its own modules, its own global state, and, since 3.12, its own GIL. Threads running in different interpreters do not contend for one lock.
The trade-off is isolation. An object created in one interpreter cannot simply be used from another. Data crosses the boundary by copying or through channel-like primitives, similar to how processes exchange data, but without separate operating-system processes. Startup is typically cheaper than starting a new process, and memory is shared at the process level. Treat that as a general tendency, not a guarantee, and measure.
From Python 3.14, the standard library has a concurrent.interpreters module, and concurrent.futures has an InterpreterPoolExecutor. These are recent, so expect some libraries to lack support. Extension modules must also be written to work with multiple interpreters.
import sys
import threading
import time
try:
from concurrent import interpreters # Python 3.14 and later
except ImportError:
sys.exit("This example needs Python 3.14 or later.")
CODE = """
total = 0
for i in range(5_000_000):
total += i
"""
def run_in_interpreter():
interp = interpreters.create()
try:
interp.exec(CODE) # runs in the calling thread, inside its own interpreter
finally:
interp.close()
if __name__ == "__main__":
start = time.perf_counter()
threads = [threading.Thread(target=run_in_interpreter) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"4 interpreters in threads: {time.perf_counter() - start:.2f}s")Each thread owns one interpreter, and each interpreter has its own GIL. On a machine with several cores, the four loops can run in parallel, even on a standard build with the GIL. Compare the time against running the same CODE four times in a row to see the effect.
Comparing the options now
The trade-offs from the earlier chapters still hold. Here is how the new options fit in:
| Need | Reasonable choice today |
|---|---|
| Waiting on network or disk | Threads or `asyncio`, on any build |
| CPU-bound work, stable and widely supported | `ProcessPoolExecutor` |
| CPU-bound work with large shared in-memory data | Free-threaded build, if all your dependencies support it |
| CPU-bound work with cheap isolation and no shared objects | Interpreters (3.14 and later), if the ecosystem you use supports them |
| Native libraries that release the GIL | Ordinary threads on any build |
Processes remain the most portable choice for CPU-bound work. The new options widen your choices, but they depend on build availability, library support, and your Python version.
A practical migration checklist
- Record your Python version and whether the build is free-threaded.
- Run your test suite under
PYTHON_GIL=0on a free-threaded build, and watch for warnings about extensions that re-enable the GIL. - Look for shared mutable state that relied on accidental atomicity, and add locks or queues.
- Time the real workload with one worker and with several, on the same build.
- Keep a process-based fallback if any required dependency lacks support.
Exercise
A team installs a free-threaded Python build and runs their CPU-bound thread pool, but sees no speedup over one thread. Name two possible causes and the check that reveals the first one.
Show answer
Possible causes: (1) the GIL was re-enabled, either by PYTHON_GIL=1 / -X gil=1 or because an imported C extension does not declare free-threading support; (2) the workload is not actually CPU-bound in Python code, for example it waits on I/O or is limited by memory bandwidth, or the work is too small to outweigh pool overhead. Print sys._is_gil_enabled() after all imports. If it returns True on a free-threaded build, the GIL is active, and the startup warnings usually name the extension responsible.
Exercise
How does the per-interpreter GIL differ from the free-threaded build in what threads can share?
Show answer
With a free-threaded build, threads share one interpreter and its Python objects, and run in parallel without a GIL. With a per-interpreter GIL, each interpreter has its own GIL and its own objects, so parallel work happens across interpreters, and data must be copied or passed between them instead of shared directly.