Debian Codegraph @

Doc/howto/free-threading-extensions.rst

raw
1 .. highlight:: c
2
3 .. _freethreading-extensions-howto:
4
5 ******************************************
6 C API Extension Support for Free Threading
7 ******************************************
8
9 Starting with the 3.13 release, CPython has experimental support for running
10 with the :term:`global interpreter lock` (GIL) disabled in a configuration
11 called :term:`free threading`. This document describes how to adapt C API
12 extensions to support free threading.
13
14
15 Identifying the Free-Threaded Build in C
16 ========================================
17
18 The CPython C API exposes the ``Py_GIL_DISABLED`` macro: in the free-threaded
19 build it's defined to ``1``, and in the regular build it's not defined.
20 You can use it to enable code that only runs under the free-threaded build::
21
22 #ifdef Py_GIL_DISABLED
23 /* code that only runs in the free-threaded build */
24 #endif
25
26 .. note::
27
28 On Windows, this macro is not defined automatically, but must be specified
29 to the compiler when building. The :func:`sysconfig.get_config_var` function
30 can be used to determine whether the current running interpreter had the
31 macro defined.
32
33
34 Module Initialization
35 =====================
36
37 Extension modules need to explicitly indicate that they support running with
38 the GIL disabled; otherwise importing the extension will raise a warning and
39 enable the GIL at runtime.
40
41 There are two ways to indicate that an extension module supports running with
42 the GIL disabled depending on whether the extension uses multi-phase or
43 single-phase initialization.
44
45 Multi-Phase Initialization
46 ..........................
47
48 Extensions that use multi-phase initialization (i.e.,
49 :c:func:`PyModuleDef_Init`) should add a :c:data:`Py_mod_gil` slot in the
50 module definition. If your extension supports older versions of CPython,
51 you should guard the slot with a :c:data:`PY_VERSION_HEX` check.
52
53 ::
54
55 static struct PyModuleDef_Slot module_slots[] = {
56 ...
57 #if PY_VERSION_HEX >= 0x030D0000
58 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
59 #endif
60 {0, NULL}
61 };
62
63 static struct PyModuleDef moduledef = {
64 PyModuleDef_HEAD_INIT,
65 .m_slots = module_slots,
66 ...
67 };
68
69
70 Single-Phase Initialization
71 ...........................
72
73 Extensions that use single-phase initialization (i.e.,
74 :c:func:`PyModule_Create`) should call :c:func:`PyUnstable_Module_SetGIL` to
75 indicate that they support running with the GIL disabled. The function is
76 only defined in the free-threaded build, so you should guard the call with
77 ``#ifdef Py_GIL_DISABLED`` to avoid compilation errors in the regular build.
78
79 ::
80
81 static struct PyModuleDef moduledef = {
82 PyModuleDef_HEAD_INIT,
83 ...
84 };
85
86 PyMODINIT_FUNC
87 PyInit_mymodule(void)
88 {
89 PyObject *m = PyModule_Create(&moduledef);
90 if (m == NULL) {
91 return NULL;
92 }
93 #ifdef Py_GIL_DISABLED
94 PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
95 #endif
96 return m;
97 }
98
99
100 General API Guidelines
101 ======================
102
103 Most of the C API is thread-safe, but there are some exceptions.
104
105 * **Struct Fields**: Accessing fields in Python C API objects or structs
106 directly is not thread-safe if the field may be concurrently modified.
107 * **Macros**: Accessor macros like :c:macro:`PyList_GET_ITEM` and
108 :c:macro:`PyList_SET_ITEM` do not perform any error checking or locking.
109 These macros are not thread-safe if the container object may be modified
110 concurrently.
111 * **Borrowed References**: C API functions that return
112 :term:`borrowed references <borrowed reference>` may not be thread-safe if
113 the containing object is modified concurrently. See the section on
114 :ref:`borrowed references <borrowed-references>` for more information.
115
116
117 Container Thread Safety
118 .......................
119
120 Containers like :c:struct:`PyListObject`,
121 :c:struct:`PyDictObject`, and :c:struct:`PySetObject` perform internal locking
122 in the free-threaded build. For example, the :c:func:`PyList_Append` will
123 lock the list before appending an item.
124
125 .. _PyDict_Next:
126
127 ``PyDict_Next``
128 '''''''''''''''
129
130 A notable exception is :c:func:`PyDict_Next`, which does not lock the
131 dictionary. You should use :c:macro:`Py_BEGIN_CRITICAL_SECTION` to protect
132 the dictionary while iterating over it if the dictionary may be concurrently
133 modified::
134
135 Py_BEGIN_CRITICAL_SECTION(dict);
136 PyObject *key, *value;
137 Py_ssize_t pos = 0;
138 while (PyDict_Next(dict, &pos, &key, &value)) {
139 ...
140 }
141 Py_END_CRITICAL_SECTION();
142
143
144 Borrowed References
145 ===================
146
147 .. _borrowed-references:
148
149 Some C API functions return :term:`borrowed references <borrowed reference>`.
150 These APIs are not thread-safe if the containing object is modified
151 concurrently. For example, it's not safe to use :c:func:`PyList_GetItem`
152 if the list may be modified concurrently.
153
154 The following table lists some borrowed reference APIs and their replacements
155 that return :term:`strong references <strong reference>`.
156
157 +-----------------------------------+-----------------------------------+
158 | Borrowed reference API | Strong reference API |
159 +===================================+===================================+
160 | :c:func:`PyList_GetItem` | :c:func:`PyList_GetItemRef` |
161 +-----------------------------------+-----------------------------------+
162 | :c:func:`PyList_GET_ITEM` | :c:func:`PyList_GetItemRef` |
163 +-----------------------------------+-----------------------------------+
164 | :c:func:`PyDict_GetItem` | :c:func:`PyDict_GetItemRef` |
165 +-----------------------------------+-----------------------------------+
166 | :c:func:`PyDict_GetItemWithError` | :c:func:`PyDict_GetItemRef` |
167 +-----------------------------------+-----------------------------------+
168 | :c:func:`PyDict_GetItemString` | :c:func:`PyDict_GetItemStringRef` |
169 +-----------------------------------+-----------------------------------+
170 | :c:func:`PyDict_SetDefault` | :c:func:`PyDict_SetDefaultRef` |
171 +-----------------------------------+-----------------------------------+
172 | :c:func:`PyDict_Next` | none (see :ref:`PyDict_Next`) |
173 +-----------------------------------+-----------------------------------+
174 | :c:func:`PyWeakref_GetObject` | :c:func:`PyWeakref_GetRef` |
175 +-----------------------------------+-----------------------------------+
176 | :c:func:`PyWeakref_GET_OBJECT` | :c:func:`PyWeakref_GetRef` |
177 +-----------------------------------+-----------------------------------+
178 | :c:func:`PyImport_AddModule` | :c:func:`PyImport_AddModuleRef` |
179 +-----------------------------------+-----------------------------------+
180
181 Not all APIs that return borrowed references are problematic. For
182 example, :c:func:`PyTuple_GetItem` is safe because tuples are immutable.
183 Similarly, not all uses of the above APIs are problematic. For example,
184 :c:func:`PyDict_GetItem` is often used for parsing keyword argument
185 dictionaries in function calls; those keyword argument dictionaries are
186 effectively private (not accessible by other threads), so using borrowed
187 references in that context is safe.
188
189 Some of these functions were added in Python 3.13. You can use the
190 `pythoncapi-compat <https://github.com/python/pythoncapi-compat>`_ package
191 to provide implementations of these functions for older Python versions.
192
193
194 .. _free-threaded-memory-allocation:
195
196 Memory Allocation APIs
197 ======================
198
199 Python's memory management C API provides functions in three different
200 :ref:`allocation domains <allocator-domains>`: "raw", "mem", and "object".
201 For thread-safety, the free-threaded build requires that only Python objects
202 are allocated using the object domain, and that all Python object are
203 allocated using that domain. This differs from the prior Python versions,
204 where this was only a best practice and not a hard requirement.
205
206 .. note::
207
208 Search for uses of :c:func:`PyObject_Malloc` in your
209 extension and check that the allocated memory is used for Python objects.
210 Use :c:func:`PyMem_Malloc` to allocate buffers instead of
211 :c:func:`PyObject_Malloc`.
212
213
214 Thread State and GIL APIs
215 =========================
216
217 Python provides a set of functions and macros to manage thread state and the
218 GIL, such as:
219
220 * :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release`
221 * :c:func:`PyEval_SaveThread` and :c:func:`PyEval_RestoreThread`
222 * :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS`
223
224 These functions should still be used in the free-threaded build to manage
225 thread state even when the :term:`GIL` is disabled. For example, if you
226 create a thread outside of Python, you must call :c:func:`PyGILState_Ensure`
227 before calling into the Python API to ensure that the thread has a valid
228 Python thread state.
229
230 You should continue to call :c:func:`PyEval_SaveThread` or
231 :c:macro:`Py_BEGIN_ALLOW_THREADS` around blocking operations, such as I/O or
232 lock acquisitions, to allow other threads to run the
233 :term:`cyclic garbage collector <garbage collection>`.
234
235
236 Protecting Internal Extension State
237 ===================================
238
239 Your extension may have internal state that was previously protected by the
240 GIL. You may need to add locking to protect this state. The approach will
241 depend on your extension, but some common patterns include:
242
243 * **Caches**: global caches are a common source of shared state. Consider
244 using a lock to protect the cache or disabling it in the free-threaded build
245 if the cache is not critical for performance.
246 * **Global State**: global state may need to be protected by a lock or moved
247 to thread local storage. C11 and C++11 provide the ``thread_local`` or
248 ``_Thread_local`` for
249 `thread-local storage <https://en.cppreference.com/w/c/language/storage_duration>`_.
250
251
252 Building Extensions for the Free-Threaded Build
253 ===============================================
254
255 C API extensions need to be built specifically for the free-threaded build.
256 The wheels, shared libraries, and binaries are indicated by a ``t`` suffix.
257
258 * `pypa/manylinux <https://github.com/pypa/manylinux>`_ supports the
259 free-threaded build, with the ``t`` suffix, such as ``python3.13t``.
260 * `pypa/cibuildwheel <https://github.com/pypa/cibuildwheel>`_ supports the
261 free-threaded build if you set
262 `CIBW_ENABLE to cpython-freethreading <https://cibuildwheel.pypa.io/en/stable/options/#enable>`_.
263
264 Limited C API and Stable ABI
265 ............................
266
267 The free-threaded build does not currently support the
268 :ref:`Limited C API <limited-c-api>` or the stable ABI. If you use
269 `setuptools <https://setuptools.pypa.io/en/latest/setuptools.html>`_ to build
270 your extension and currently set ``py_limited_api=True`` you can use
271 ``py_limited_api=not sysconfig.get_config_var("Py_GIL_DISABLED")`` to opt out
272 of the limited API when building with the free-threaded build.
273
274 .. note::
275 You will need to build separate wheels specifically for the free-threaded
276 build. If you currently use the stable ABI, you can continue to build a
277 single wheel for multiple non-free-threaded Python versions.
278
279
280 Windows
281 .......
282
283 Due to a limitation of the official Windows installer, you will need to
284 manually define ``Py_GIL_DISABLED=1`` when building extensions from source.
285
286 .. seealso::
287
288 `Porting Extension Modules to Support Free-Threading
289 <https://py-free-threading.github.io/porting/>`_:
290 A community-maintained porting guide for extension authors.