C API Extension Support for Free Threading
¶
Starting with the 3.13 release, CPython has experimental support for running with the
全局解释器锁
(GIL) disabled in a configuration called
free threading
. This document describes how to adapt C API extensions to support free threading.
Identifying the Free-Threaded Build in C
¶
The CPython C API exposes the
Py_GIL_DISABLED
macro: in the free-threaded build it’s defined to
1
, and in the regular build it’s not defined. You can use it to enable code that only runs under the free-threaded build:
#ifdef Py_GIL_DISABLED
/* code that only runs in the free-threaded build */
#endif
Module Initialization
¶
Extension modules need to explicitly indicate that they support running with the GIL disabled; otherwise importing the extension will raise a warning and enable the GIL at runtime.
There are two ways to indicate that an extension module supports running with the GIL disabled depending on whether the extension uses multi-phase or single-phase initialization.
Multi-Phase Initialization
¶
Extensions that use multi-phase initialization (i.e.,
PyModuleDef_Init()
) should add a
Py_mod_gil
slot in the module definition. If your extension supports older versions of CPython, you should guard the slot with a
PY_VERSION_HEX
check.
static struct PyModuleDef_Slot module_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_slots = module_slots,
...
};