Sub topic 1
What the GIL Is and Why CPython Has One
Prerequisites
This chapter assumes basic Python functions, familiarity with threading or concurrent.futures, and a basic understanding of threads, processes, and race conditions.
The GIL and CPython
The Global Interpreter Lock (GIL) is a lock in the standard CPython interpreter. It allows only one thread at a time to execute Python bytecode in a process.
CPython uses the GIL partly to protect interpreter data structures, such as reference counts. Reference counting tracks how many names refer to an object. With one thread changing these counts at a time, the interpreter avoids many low-level memory races and keeps much existing C extension code simpler.
The GIL does not make all Python code thread-safe. It only serializes some interpreter operations. A sequence such as “read a value, calculate a new value, write the value” can still produce a race when its steps are interleaved.
CPU-Bound Threads Under the GIL
A CPU-bound task spends most of its time calculating rather than waiting for input or output. In standard CPython, four CPU-bound threads generally cannot execute Python bytecode on four cores at the same time. They take turns holding the GIL.
Threads can still help with I/O-bound work because the interpreter can release the GIL while a thread waits for a file, socket, or other external operation. For CPU-bound work, multiprocessing has traditionally provided parallelism by using separate interpreter processes.
> callout note > The GIL is a CPython implementation detail. Other Python implementations may use different execution models.
PEP 703 and Free-Threaded Python
PEP 703 proposed making the GIL optional. The accepted work introduced a free-threaded CPython build, which can run Python bytecode concurrently on multiple cores. This build became available as an experimental option in Python 3.13, and its compatibility and performance continue to evolve.
Removing the GIL changes an important assumption: ordinary Python operations are no longer globally serialized. Code that shares mutable state must use explicit synchronization or a safer design.
Getting and Detecting the Build
A free-threaded build is commonly identified with a t suffix, such as python3.13t. Check both the build and the current GIL state:
import sys
import sysconfig
print("Free-threaded build:",
sysconfig.get_config_var("Py_GIL_DISABLED"))
print("GIL enabled:",
getattr(sys, "_is_gil_enabled", lambda: True)())Exercise
Why can I/O-bound threads help under the GIL while CPU-bound threads usually do not?
Show answer
I/O-bound threads can release the GIL while waiting, allowing another thread to run. CPU-bound Python threads spend their time competing for the GIL.