Sub topic 2
Turning the GIL on and off at runtime
Assume you know Python functions, threading, concurrent.futures, and the difference between processes and threads. This chapter focuses on free-threaded CPython, the build that can run without the Global Interpreter Lock (GIL).
Selecting the GIL mode
A free-threaded build can start with the GIL enabled or disabled. The setting is chosen when Python starts. It is not a switch that ordinary Python code can safely flip while the program is running.
Use the PYTHON_GIL environment variable or the -X gil option:
# Disable the GIL in a free-threaded build
PYTHON_GIL=0 python3.13t script.py
python3.13t -X gil=0 script.py
# Enable the GIL
PYTHON_GIL=1 python3.13t script.pyA standard build cannot become free-threaded just because PYTHON_GIL=0 is set. Detect both the build and the current mode:
import sys
import sysconfig
print("Free-threaded build:",
sysconfig.get_config_var("Py_GIL_DISABLED"))
print("GIL enabled:", sys._is_gil_enabled())Running CPU-bound work in parallel
With the GIL enabled, only one thread at a time executes Python bytecode in standard CPython. A free-threaded build can execute CPU-bound Python code on multiple cores:
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(is_prime(n) for n in range(limit))
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(count_primes, [200_000] * 4)))Built-ins do not make compound actions safe
Free-threaded Python preserves useful safety properties for many individual operations on built-in types. However, a sequence of operations is not automatically atomic. This check-then-act code can race:
if key not in shared:
shared[key] = create_value()Another thread may change shared between the two statements. Protect shared state explicitly:
import threading
counter = 0
lock = threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock:
counter += 1Use queues for ownership transfer, thread-local data for per-thread state, and immutable values when possible.
Exercise
Why does counter += 1 need a lock in free-threaded Python?
Show answer
It is a read-modify-write sequence, so another thread can intervene between the read and the write.