Sub topic 11
C extensions and the GIL re-enabling rule
This chapter assumes you have read the earlier chapters on detecting the free-threaded build and controlling the GIL with PYTHON_GIL. It also assumes you know what a C extension module is: a shared library, such as a .so or .pyd file, that Python imports like any other module. You don't need to write C to follow most of it.
Why extensions are a problem
Many C extensions rely on the GIL without saying so. Take a C function that increments a global counter or edits a shared buffer. Under the GIL, only one thread runs Python-level code at a time, so the author never needed a lock. Remove the GIL and two threads can enter that function at once, corrupting memory. In C this means crashes and silent data corruption, not just a wrong number.
The CPython developers can't audit every extension on PyPI. They chose a conservative default instead: an extension is assumed unsafe without the GIL until it says otherwise.
The re-enabling rule
On a free-threaded build, the GIL starts disabled. When you import an extension module that has not declared free-threading support, the interpreter does two things:
- It turns the GIL back on for the whole process.
- It emits a
RuntimeWarning.
The warning looks like this:
RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module 'legacy_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 rule is process-wide. One legacy extension re-enables the GIL for every thread, including threads that never touch that extension. In Python 3.13, the GIL stays on after the import for the rest of the process.
Observing the rule from Python
You can check what an import does to the GIL without reading any C. The script below imports a module by name and reports the GIL state before and after, along with any warning.
import importlib
import sys
import warnings
def check_gil_after_import(module_name):
if not hasattr(sys, "_is_gil_enabled"):
print("This interpreter has no sys._is_gil_enabled (older than 3.13).")
return
before = sys._is_gil_enabled()
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
importlib.import_module(module_name)
after = sys._is_gil_enabled()
print(f"{module_name}: GIL before={before}, after={after}")
for w in caught:
if issubclass(w.category, RuntimeWarning) and "global interpreter lock" in str(w.message):
print(" re-enabled the GIL:", w.message)
if __name__ == "__main__":
# Pure-Python and stdlib modules do not trigger the rule.
check_gil_after_import("json")
# Replace with the extension you want to test, for example "numpy".
for name in sys.argv[1:]:
check_gil_after_import(name)Run it as python3.13t check_gil.py numpy. If the GIL goes from False to True, that module (or something it imports) has not declared support. Check dependencies of the extension too, because the rule applies to every extension module loaded as part of the import.
For a stricter test in CI, turn the warning into an error:
python3.13t -W error::RuntimeWarning -c "import numpy"The import fails if any module tries to re-enable the GIL.
Declaring support: the `Py_mod_gil` slot
An extension opts in by declaring a module slot named Py_mod_gil with the value Py_MOD_GIL_NOT_USED. This is a promise from the author that the module's code is safe to run from several threads at once. The other value, Py_MOD_GIL_USED, is the default and means "I still need the GIL."
This works with multi-phase initialization, where the module defines a PyModuleDef with a slots array. Here is a small complete module.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *
add_one(PyObject *self, PyObject *arg)
{
long value = PyLong_AsLong(arg);
if (value == -1 && PyErr_Occurred()) {
return NULL;
}
return PyLong_FromLong(value + 1);
}
static PyMethodDef methods[] = {
{"add_one", add_one, METH_O, "Return the argument plus one."},
{NULL, NULL, 0, NULL}
};
static PyModuleDef_Slot slots[] = {
#if PY_VERSION_HEX >= 0x030D0000
{Py_mod_gil, Py_MOD_GIL_NOT_USED},
#endif
{0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
.m_name = "addone",
.m_doc = "A stateless example module.",
.m_size = 0,
.m_methods = methods,
.m_slots = slots,
};
PyMODINIT_FUNC
PyInit_addone(void)
{
return PyModuleDef_Init(&moduledef);
}This module is safe because add_one keeps no global state. It only reads its argument and returns a new object. The PY_VERSION_HEX guard keeps the file compiling on Python versions before 3.13, which don't know the slot.
Modules that use single-phase initialization (calling PyModule_Create directly) can't use a slot. They call PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED) after creating the module.
Declaring from other tools
Most authors don't write raw C. Each major binding tool has its own switch:
| Tool | How to declare free-threading support |
|---|---|
| Cython (3.1 and later) | `# cython: freethreading_compatible=True` at the top of the `.pyx` file |
| pybind11 (2.13 and later) | `PYBIND11_MODULE(name, m, py::mod_gil_not_used())` |
| PyO3 (0.23 and later) | `#[pymodule(gil_used = false)]` |
Check each tool's documentation for the exact current syntax before relying on it.
A declaration is a promise, not a fix
Setting Py_MOD_GIL_NOT_USED does not make the code thread-safe. It only stops the interpreter from protecting you. Before declaring, the author must audit the code for these common problems.
- Global and static variables. C-level state shared across calls needs a lock, an atomic type, or a move into per-thread or per-module storage.
- Borrowed references. APIs such as
PyList_GetItemandPyDict_GetItemreturn a reference you don't own. Another thread can delete the item and free it while you still hold the pointer. Use the strong-reference variants added in 3.13, such asPyList_GetItemRefandPyDict_GetItemRef. - Mutating shared Python objects. Code that walks a list or dict while other threads change it needs protection. CPython provides critical-section macros,
Py_BEGIN_CRITICAL_SECTION(obj)andPy_END_CRITICAL_SECTION(), which lock a single object. It also providesPyMutexfor your own state. - Assumptions about releasing the GIL. Old code often assumes that nothing else runs between two C API calls unless it released the GIL itself. That assumption no longer holds.
Here is a short example of guarding extension-owned state with PyMutex:
static PyMutex counter_mutex = {0};
static long counter = 0;
static PyObject *
next_id(PyObject *self, PyObject *unused)
{
long value;
PyMutex_Lock(&counter_mutex);
value = ++counter;
PyMutex_Unlock(&counter_mutex);
return PyLong_FromLong(value);
}Without the mutex, two threads could read the same value of counter and return duplicate IDs.
Build and packaging differences
The free-threaded build is a separate ABI. Three consequences follow:
- Extensions must be compiled against the free-threaded headers. The file name carries a
ttag, for exampleaddone.cpython-313t-x86_64-linux-gnu.so. - Wheels use the
cp313ttag. A normalcp313wheel will not install on a free-threaded interpreter. - In 3.13 the free-threaded build does not support the limited API or stable ABI (
abi3). Each extension needs its own build for it.
This means library maintainers must publish extra wheels. Until they do, pip may fall back to compiling from source, which can fail without a compiler or headers.
Assessing a dependency
For each compiled dependency in your project, work through these steps:
- Look for a
cp313twheel on PyPI for the version you use. - Read the project's release notes or documentation for a statement on free-threading support. Several projects publish a compatibility tracker.
- Install it on a free-threaded interpreter and run
python3.13t -W error::RuntimeWarning -c "import yourdep". - Run your own tests with
PYTHON_GIL=0and several threads. Passing the import check only shows that the extension declares support, not that it is correct.
Be careful with PYTHON_GIL=0 as a workaround. It silences the warning and keeps the GIL off for an extension whose author never promised safety, so crashes and corrupted data are possible. Use it to test, not to ship.
Summary of the rule
- Free-threaded CPython assumes an extension needs the GIL unless it declares otherwise.
- Importing an undeclared extension turns the GIL on for the whole process and emits a
RuntimeWarning. - Authors declare support with
Py_mod_gilset toPy_MOD_GIL_NOT_USED, or with the equivalent setting in Cython, pybind11 or PyO3. - Declaring support is a promise that requires auditing globals, borrowed references and shared-object access.
PYTHON_GIL=0overrides the rule, with the risks described above.
Exercise
You run a program on python3.13t with 8 worker threads doing CPU-bound pure-Python work. After you add import some_legacy_ext at the top, the program prints a RuntimeWarning about the GIL and runs no faster than a single thread. Explain why, and name two ways to restore parallelism.
Show answer
The extension has not declared PyMODGILNOTUSED, so importing it re-enables the GIL for the whole process, and the 8 threads are serialized again even though most of them never call the extension. Two fixes: (1) replace or upgrade the extension to a version that declares free-threading support (a cp313t wheel), or (2) move the legacy extension into a separate process so the main process never imports it. Forcing PYTHON_GIL=0 would also keep the GIL off, but only if you have verified the extension is safe to call from multiple threads.
Exercise
A module's slots array contains {Pymodgil, PyMODGILNOTUSED}, and its C function increments a static long without any lock. Is the module safe under free-threading? What should change?
Show answer
No. The slot is only a declaration, and the unprotected static variable is a data race when two threads call the function at once. Protect the counter with a PyMutex (PyMutexLock and PyMutexUnlock around the increment), use an atomic operation, or remove the shared state.