Sub topic 5
Turning the GIL on and off at runtime
This chapter assumes you can read basic Python and have used threading or concurrent.futures. You should also know what the GIL is and how a free-threaded build differs from a standard one, both covered in earlier chapters. Here you learn how to control the GIL on a free-threaded interpreter, how to check what it is doing, and why the answer can change while your program runs.
The GIL is a startup decision, with one exception
"Runtime" can mislead here. You cannot flip the GIL on and off from inside a running program. The interpreter decides whether the GIL is enabled while it starts up, using these inputs:
- The build type. A standard build always has the GIL. A free-threaded build (for example
python3.13t) can run either way. - The
-X gil=...command-line option. - The
PYTHON_GILenvironment variable. - The modules you import. A module that has not declared itself safe without the GIL can make the interpreter turn the GIL on after startup.
The last input is the exception. Python 3.13 can turn the GIL on in the middle of a run, but it never turns it back off. So the GIL setting is chosen when the process starts, and it only moves in one direction after that.
The control knobs
You have two ways to set the GIL state at startup.
# Run with the GIL disabled (free-threaded build, e.g. python3.13t)
PYTHON_GIL=0 python3.13t script.py
# Equivalent command-line option
python3.13t -X gil=0 script.py
# Force the GIL on, even on a free-threaded build
PYTHON_GIL=1 python3.13t script.pyBoth knobs take 0 or 1. The table shows what each setting does on a free-threaded build.
| Setting | Effect on a free-threaded build |
|---|---|
| Nothing set | The GIL starts disabled. It is turned on if you import an extension that does not declare GIL-free support. |
| `PYTHON_GIL=0` or `-X gil=0` | The GIL stays disabled, even if you import an extension that has not declared support. |
| `PYTHON_GIL=1` or `-X gil=1` | The GIL is enabled from the start and behaves as in a standard build. |
The -X option and the environment variable do the same job. If both are given, the command-line option wins, which is the usual rule for CPython's -X options.
Some practical differences between the two:
- An environment variable is inherited by child processes. If your program starts subprocesses with
subprocess, they seePYTHON_GILtoo. A-Xoption applies only to the interpreter you launch with it. - The environment variable is convenient in CI configuration, Dockerfiles, and shell sessions. The
-Xoption is convenient in a shebang line or a one-off command. - Setting
os.environ["PYTHON_GIL"] = "0"inside a script does nothing for the current process. The interpreter read the variable before your first line ran. It only affects subprocesses you start afterwards.
A standard build is a different case. It has no way to run without the GIL, so asking it to disable the GIL is an error, not something it ignores. Treat the 0 setting as meaningful only on python3.13t and other free-threaded builds. Exact behavior here varies between versions, so test it on the interpreter you ship.
Checking the current state
The previous chapter showed how to detect a free-threaded build. Detecting the build is not enough, because a free-threaded build can still have the GIL on. You need to check two separate facts:
sysconfig.get_config_var("Py_GIL_DISABLED")tells you what the interpreter was built as. It does not change while the program runs.sys._is_gil_enabled()tells you whether the GIL is active right now.
import sys
import sysconfig
# 1 on a free-threaded build, 0 or None on a standard build
print("Free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED"))
# Whether the GIL is active in this running interpreter
print("GIL enabled:", sys._is_gil_enabled())On python3.13t with no settings, this prints 1 and False. On a standard build, it prints 0 (or None) and True. With PYTHON_GIL=1 python3.13t, it prints 1 and True. That last combination is the one people tend to forget: a free-threaded build that is running with the GIL.
The function sys._is_gil_enabled exists from Python 3.13 on. Its leading underscore marks it as a semi-private helper, so wrap it if your code must also run on older versions:
import sys
def gil_enabled() -> bool:
"""Return True if the GIL is active; older Pythons always have one."""
check = getattr(sys, "_is_gil_enabled", None)
return True if check is None else check()
if __name__ == "__main__":
print("GIL enabled:", gil_enabled())Why the GIL can turn itself back on
Extension modules written in C are compiled against the interpreter's internals. Many were written assuming that the GIL protects their global state. If such a module ran with real parallel threads, it could corrupt memory or crash.
To protect you, a free-threaded build asks each extension module to declare that it is safe without the GIL. This is done with a module slot named Py_mod_gil. An extension that sets the slot to "not used" is declaring support. An extension that does not set it is assumed to need the GIL.
When you import an extension without the declaration, the interpreter does three things:
- It turns the GIL on for the whole process.
- It emits a
RuntimeWarningnaming the module. - It keeps the GIL on until the process exits.
The warning reads roughly like this:
RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module 'example_ext', which has not declared that it can run safely without the GIL. To override this behavior and keep the GIL disabled (at your own risk), run with PYTHON_GIL=0 or -X gil=0.The re-enabling rule applies to the whole process, not to a single thread. One legacy extension imported by one corner of your program takes parallelism away from everything. That is why the earlier checks matter.
The flow below summarizes the decision.
Using `PYTHON_GIL=0` safely
Setting PYTHON_GIL=0 suppresses the re-enabling. The interpreter trusts you instead of the extension. This is useful in two situations:
- You are testing whether an extension that lacks the declaration actually works without the GIL.
- You have verified that a particular extension is safe in your usage and want the parallelism now.
It is also the riskier choice. If the extension does depend on the GIL, you can get data corruption or crashes that appear only under load and are hard to reproduce. The warning text says "at your own risk" for a reason.
A practical workflow
Putting the pieces together, here is a routine for evaluating a program on a free-threaded build.
- Run it with no settings and look at stderr. If a
RuntimeWarningabout the GIL appears, note which module it names. - Print
sys._is_gil_enabled()at the end of startup, after all imports. If it isTrue, the GIL got turned on, and your threads will not run in parallel. - Run the same program with
PYTHON_GIL=1and time it. This gives a fair baseline on the same interpreter. - Run it with
PYTHON_GIL=0and time it again. Compare the two. - If step 4 is faster, you have parallelism. If it crashes or gives different results, suspect an extension (or your own code) that relied on the GIL.
You can run the CPU-bound pool example from the spine in steps 3 and 4:
from concurrent.futures import ThreadPoolExecutor
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(count_primes, [200_000] * 4))
print(results)With the GIL on, the four tasks take turns, so the total time is roughly four times one task. With the GIL off and at least four free cores, the wall-clock time should be closer to one task, although a free-threaded build is slower per thread than a standard one, so the gain is less than four times.
Common mistakes
- Assuming the
tbuild means no GIL. A free-threaded build can have the GIL on because ofPYTHON_GIL=1or an import. Always checksys._is_gil_enabled(). - Checking only at the top of the script. A later import can change the answer.
- Setting the variable too late. Assigning to
os.environinside the script does not affect the running interpreter. - Forgetting subprocesses. The environment variable reaches child processes, while a
-Xoption does not. A worker process may run with a different GIL setting than its parent. - Treating the warning as noise. It tells you that parallelism is lost, or that you are running unsupported.
Exercise
You run python3.13t app.py, and your program prints Free-threaded build: 1 and GIL enabled: True. Give two different causes, and say which setting or check would tell them apart.
Show answer
One cause is that PYTHON_GIL=1 or -X gil=1 was set, which forces the GIL on from startup. The other is that the program imported a C extension that has not declared GIL-free support, so the interpreter turned the GIL on and printed a RuntimeWarning naming the module. To tell them apart, check the environment and the command line for PYTHON_GIL or -X gil, and look at stderr for the warning. Running with PYTHON_GIL=0 shows whether the extension is the cause, but only do that to test.
Exercise
Why does os.environ["PYTHON_GIL"] = "0" placed at the top of a script fail to disable the GIL for that script, and when does it still have an effect?
Show answer
The interpreter reads PYTHON_GIL once during startup, before any of your code runs, so changing it afterwards does not change the current process. It still affects any subprocess started later, because child processes read the environment when they start.