Debian Codegraph @

Doc/c-api/init.rst

raw
1 .. highlight:: c
2
3
4 .. _initialization:
5
6 *****************************************
7 Initialization, Finalization, and Threads
8 *****************************************
9
10 See :ref:`Python Initialization Configuration <init-config>` for details
11 on how to configure the interpreter prior to initialization.
12
13 .. _pre-init-safe:
14
15 Before Python Initialization
16 ============================
17
18 In an application embedding Python, the :c:func:`Py_Initialize` function must
19 be called before using any other Python/C API functions; with the exception of
20 a few functions and the :ref:`global configuration variables
21 <global-conf-vars>`.
22
23 The following functions can be safely called before Python is initialized:
24
25 * Functions that initialize the interpreter:
26
27 * :c:func:`Py_Initialize`
28 * :c:func:`Py_InitializeEx`
29 * :c:func:`Py_InitializeFromConfig`
30 * :c:func:`Py_BytesMain`
31 * :c:func:`Py_Main`
32 * the runtime pre-initialization functions covered in :ref:`init-config`
33
34 * Configuration functions:
35
36 * :c:func:`PyImport_AppendInittab`
37 * :c:func:`PyImport_ExtendInittab`
38 * :c:func:`!PyInitFrozenExtensions`
39 * :c:func:`PyMem_SetAllocator`
40 * :c:func:`PyMem_SetupDebugHooks`
41 * :c:func:`PyObject_SetArenaAllocator`
42 * :c:func:`Py_SetProgramName`
43 * :c:func:`Py_SetPythonHome`
44 * :c:func:`PySys_ResetWarnOptions`
45 * the configuration functions covered in :ref:`init-config`
46
47 * Informative functions:
48
49 * :c:func:`Py_IsInitialized`
50 * :c:func:`PyMem_GetAllocator`
51 * :c:func:`PyObject_GetArenaAllocator`
52 * :c:func:`Py_GetBuildInfo`
53 * :c:func:`Py_GetCompiler`
54 * :c:func:`Py_GetCopyright`
55 * :c:func:`Py_GetPlatform`
56 * :c:func:`Py_GetVersion`
57 * :c:func:`Py_IsInitialized`
58
59 * Utilities:
60
61 * :c:func:`Py_DecodeLocale`
62 * the status reporting and utility functions covered in :ref:`init-config`
63
64 * Memory allocators:
65
66 * :c:func:`PyMem_RawMalloc`
67 * :c:func:`PyMem_RawRealloc`
68 * :c:func:`PyMem_RawCalloc`
69 * :c:func:`PyMem_RawFree`
70
71 * Synchronization:
72
73 * :c:func:`PyMutex_Lock`
74 * :c:func:`PyMutex_Unlock`
75
76 .. note::
77
78 Despite their apparent similarity to some of the functions listed above,
79 the following functions **should not be called** before the interpreter has
80 been initialized: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`,
81 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
82 :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`,
83 :c:func:`Py_GetProgramName`, :c:func:`PyEval_InitThreads`, and
84 :c:func:`Py_RunMain`.
85
86
87 .. _global-conf-vars:
88
89 Global configuration variables
90 ==============================
91
92 Python has variables for the global configuration to control different features
93 and options. By default, these flags are controlled by :ref:`command line
94 options <using-on-interface-options>`.
95
96 When a flag is set by an option, the value of the flag is the number of times
97 that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
98 to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
99
100 .. c:var:: int Py_BytesWarningFlag
101
102 This API is kept for backward compatibility: setting
103 :c:member:`PyConfig.bytes_warning` should be used instead, see :ref:`Python
104 Initialization Configuration <init-config>`.
105
106 Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
107 :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
108 or equal to ``2``.
109
110 Set by the :option:`-b` option.
111
112 .. deprecated-removed:: 3.12 3.14
113
114 .. c:var:: int Py_DebugFlag
115
116 This API is kept for backward compatibility: setting
117 :c:member:`PyConfig.parser_debug` should be used instead, see :ref:`Python
118 Initialization Configuration <init-config>`.
119
120 Turn on parser debugging output (for expert only, depending on compilation
121 options).
122
123 Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
124 variable.
125
126 .. deprecated-removed:: 3.12 3.14
127
128 .. c:var:: int Py_DontWriteBytecodeFlag
129
130 This API is kept for backward compatibility: setting
131 :c:member:`PyConfig.write_bytecode` should be used instead, see :ref:`Python
132 Initialization Configuration <init-config>`.
133
134 If set to non-zero, Python won't try to write ``.pyc`` files on the
135 import of source modules.
136
137 Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
138 environment variable.
139
140 .. deprecated-removed:: 3.12 3.14
141
142 .. c:var:: int Py_FrozenFlag
143
144 This API is kept for backward compatibility: setting
145 :c:member:`PyConfig.pathconfig_warnings` should be used instead, see
146 :ref:`Python Initialization Configuration <init-config>`.
147
148 Suppress error messages when calculating the module search path in
149 :c:func:`Py_GetPath`.
150
151 Private flag used by ``_freeze_module`` and ``frozenmain`` programs.
152
153 .. deprecated-removed:: 3.12 3.14
154
155 .. c:var:: int Py_HashRandomizationFlag
156
157 This API is kept for backward compatibility: setting
158 :c:member:`PyConfig.hash_seed` and :c:member:`PyConfig.use_hash_seed` should
159 be used instead, see :ref:`Python Initialization Configuration
160 <init-config>`.
161
162 Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
163 a non-empty string.
164
165 If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
166 variable to initialize the secret hash seed.
167
168 .. deprecated-removed:: 3.12 3.14
169
170 .. c:var:: int Py_IgnoreEnvironmentFlag
171
172 This API is kept for backward compatibility: setting
173 :c:member:`PyConfig.use_environment` should be used instead, see
174 :ref:`Python Initialization Configuration <init-config>`.
175
176 Ignore all :envvar:`!PYTHON*` environment variables, e.g.
177 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
178
179 Set by the :option:`-E` and :option:`-I` options.
180
181 .. deprecated-removed:: 3.12 3.14
182
183 .. c:var:: int Py_InspectFlag
184
185 This API is kept for backward compatibility: setting
186 :c:member:`PyConfig.inspect` should be used instead, see
187 :ref:`Python Initialization Configuration <init-config>`.
188
189 When a script is passed as first argument or the :option:`-c` option is used,
190 enter interactive mode after executing the script or the command, even when
191 :data:`sys.stdin` does not appear to be a terminal.
192
193 Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
194 variable.
195
196 .. deprecated-removed:: 3.12 3.14
197
198 .. c:var:: int Py_InteractiveFlag
199
200 This API is kept for backward compatibility: setting
201 :c:member:`PyConfig.interactive` should be used instead, see
202 :ref:`Python Initialization Configuration <init-config>`.
203
204 Set by the :option:`-i` option.
205
206 .. deprecated-removed:: 3.12 3.15
207
208 .. c:var:: int Py_IsolatedFlag
209
210 This API is kept for backward compatibility: setting
211 :c:member:`PyConfig.isolated` should be used instead, see
212 :ref:`Python Initialization Configuration <init-config>`.
213
214 Run Python in isolated mode. In isolated mode :data:`sys.path` contains
215 neither the script's directory nor the user's site-packages directory.
216
217 Set by the :option:`-I` option.
218
219 .. versionadded:: 3.4
220
221 .. deprecated-removed:: 3.12 3.14
222
223 .. c:var:: int Py_LegacyWindowsFSEncodingFlag
224
225 This API is kept for backward compatibility: setting
226 :c:member:`PyPreConfig.legacy_windows_fs_encoding` should be used instead, see
227 :ref:`Python Initialization Configuration <init-config>`.
228
229 If the flag is non-zero, use the ``mbcs`` encoding with ``replace`` error
230 handler, instead of the UTF-8 encoding with ``surrogatepass`` error handler,
231 for the :term:`filesystem encoding and error handler`.
232
233 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
234 variable is set to a non-empty string.
235
236 See :pep:`529` for more details.
237
238 .. availability:: Windows.
239
240 .. deprecated-removed:: 3.12 3.14
241
242 .. c:var:: int Py_LegacyWindowsStdioFlag
243
244 This API is kept for backward compatibility: setting
245 :c:member:`PyConfig.legacy_windows_stdio` should be used instead, see
246 :ref:`Python Initialization Configuration <init-config>`.
247
248 If the flag is non-zero, use :class:`io.FileIO` instead of
249 :class:`!io._WindowsConsoleIO` for :mod:`sys` standard streams.
250
251 Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
252 variable is set to a non-empty string.
253
254 See :pep:`528` for more details.
255
256 .. availability:: Windows.
257
258 .. deprecated-removed:: 3.12 3.14
259
260 .. c:var:: int Py_NoSiteFlag
261
262 This API is kept for backward compatibility: setting
263 :c:member:`PyConfig.site_import` should be used instead, see
264 :ref:`Python Initialization Configuration <init-config>`.
265
266 Disable the import of the module :mod:`site` and the site-dependent
267 manipulations of :data:`sys.path` that it entails. Also disable these
268 manipulations if :mod:`site` is explicitly imported later (call
269 :func:`site.main` if you want them to be triggered).
270
271 Set by the :option:`-S` option.
272
273 .. deprecated-removed:: 3.12 3.14
274
275 .. c:var:: int Py_NoUserSiteDirectory
276
277 This API is kept for backward compatibility: setting
278 :c:member:`PyConfig.user_site_directory` should be used instead, see
279 :ref:`Python Initialization Configuration <init-config>`.
280
281 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
282 :data:`sys.path`.
283
284 Set by the :option:`-s` and :option:`-I` options, and the
285 :envvar:`PYTHONNOUSERSITE` environment variable.
286
287 .. deprecated-removed:: 3.12 3.14
288
289 .. c:var:: int Py_OptimizeFlag
290
291 This API is kept for backward compatibility: setting
292 :c:member:`PyConfig.optimization_level` should be used instead, see
293 :ref:`Python Initialization Configuration <init-config>`.
294
295 Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
296 variable.
297
298 .. deprecated-removed:: 3.12 3.14
299
300 .. c:var:: int Py_QuietFlag
301
302 This API is kept for backward compatibility: setting
303 :c:member:`PyConfig.quiet` should be used instead, see :ref:`Python
304 Initialization Configuration <init-config>`.
305
306 Don't display the copyright and version messages even in interactive mode.
307
308 Set by the :option:`-q` option.
309
310 .. versionadded:: 3.2
311
312 .. deprecated-removed:: 3.12 3.14
313
314 .. c:var:: int Py_UnbufferedStdioFlag
315
316 This API is kept for backward compatibility: setting
317 :c:member:`PyConfig.buffered_stdio` should be used instead, see :ref:`Python
318 Initialization Configuration <init-config>`.
319
320 Force the stdout and stderr streams to be unbuffered.
321
322 Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
323 environment variable.
324
325 .. deprecated-removed:: 3.12 3.14
326
327 .. c:var:: int Py_VerboseFlag
328
329 This API is kept for backward compatibility: setting
330 :c:member:`PyConfig.verbose` should be used instead, see :ref:`Python
331 Initialization Configuration <init-config>`.
332
333 Print a message each time a module is initialized, showing the place
334 (filename or built-in module) from which it is loaded. If greater or equal
335 to ``2``, print a message for each file that is checked for when
336 searching for a module. Also provides information on module cleanup at exit.
337
338 Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
339 variable.
340
341 .. deprecated-removed:: 3.12 3.14
342
343
344 Initializing and finalizing the interpreter
345 ===========================================
346
347
348 .. c:function:: void Py_Initialize()
349
350 .. index::
351 single: PyEval_InitThreads()
352 single: modules (in module sys)
353 single: path (in module sys)
354 pair: module; builtins
355 pair: module; __main__
356 pair: module; sys
357 triple: module; search; path
358 single: Py_FinalizeEx (C function)
359
360 Initialize the Python interpreter. In an application embedding Python,
361 this should be called before using any other Python/C API functions; see
362 :ref:`Before Python Initialization <pre-init-safe>` for the few exceptions.
363
364 This initializes the table of loaded modules (``sys.modules``), and creates
365 the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.
366 It also initializes the module search path (``sys.path``). It does not set
367 ``sys.argv``; use the :ref:`Python Initialization Configuration <init-config>`
368 API for that. This is a no-op when called for a second time (without calling
369 :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal
370 error if the initialization fails.
371
372 Use :c:func:`Py_InitializeFromConfig` to customize the
373 :ref:`Python Initialization Configuration <init-config>`.
374
375 .. note::
376 On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``,
377 which will also affect non-Python uses of the console using the C Runtime.
378
379
380 .. c:function:: void Py_InitializeEx(int initsigs)
381
382 This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
383 *initsigs* is ``0``, it skips initialization registration of signal handlers,
384 which may be useful when CPython is embedded as part of a larger application.
385
386 Use :c:func:`Py_InitializeFromConfig` to customize the
387 :ref:`Python Initialization Configuration <init-config>`.
388
389
390 .. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
391
392 Initialize Python from *config* configuration, as described in
393 :ref:`init-from-config`.
394
395 See the :ref:`init-config` section for details on pre-initializing the
396 interpreter, populating the runtime configuration structure, and querying
397 the returned status structure.
398
399
400 .. c:function:: int Py_IsInitialized()
401
402 Return true (nonzero) when the Python interpreter has been initialized, false
403 (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
404 :c:func:`Py_Initialize` is called again.
405
406
407 .. c:function:: int Py_IsFinalizing()
408
409 Return true (non-zero) if the main Python interpreter is
410 :term:`shutting down <interpreter shutdown>`. Return false (zero) otherwise.
411
412 .. versionadded:: 3.13
413
414
415 .. c:function:: int Py_FinalizeEx()
416
417 Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
418 Python/C API functions, and destroy all sub-interpreters (see
419 :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
420 the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory
421 allocated by the Python interpreter. This is a no-op when called for a second
422 time (without calling :c:func:`Py_Initialize` again first).
423
424 Since this is the reverse of :c:func:`Py_Initialize`, it should be called
425 in the same thread with the same interpreter active. That means
426 the main thread and the main interpreter.
427 This should never be called while :c:func:`Py_RunMain` is running.
428
429 Normally the return value is ``0``.
430 If there were errors during finalization (flushing buffered data),
431 ``-1`` is returned.
432
433 This function is provided for a number of reasons. An embedding application
434 might want to restart Python without having to restart the application itself.
435 An application that has loaded the Python interpreter from a dynamically
436 loadable library (or DLL) might want to free all memory allocated by Python
437 before unloading the DLL. During a hunt for memory leaks in an application a
438 developer might want to free all memory allocated by Python before exiting from
439 the application.
440
441 **Bugs and caveats:** The destruction of modules and objects in modules is done
442 in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail
443 when they depend on other objects (even functions) or modules. Dynamically
444 loaded extension modules loaded by Python are not unloaded. Small amounts of
445 memory allocated by the Python interpreter may not be freed (if you find a leak,
446 please report it). Memory tied up in circular references between objects is not
447 freed. Some memory allocated by extension modules may not be freed. Some
448 extensions may not work properly if their initialization routine is called more
449 than once; this can happen if an application calls :c:func:`Py_Initialize` and
450 :c:func:`Py_FinalizeEx` more than once. :c:func:`Py_FinalizeEx` must not be
451 called recursively from within itself. Therefore, it must not be called by
452 any code that may be run as part of the interpreter shutdown process, such
453 as :py:mod:`atexit` handlers, object finalizers, or any code that may be run
454 while flushing the stdout and stderr files.
455
456 .. audit-event:: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx
457
458 .. versionadded:: 3.6
459
460
461 .. c:function:: void Py_Finalize()
462
463 This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
464 disregards the return value.
465
466
467 .. c:function:: int Py_BytesMain(int argc, char **argv)
468
469 Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings,
470 allowing the calling application to delegate the text decoding step to
471 the CPython runtime.
472
473 .. versionadded:: 3.8
474
475
476 .. c:function:: int Py_Main(int argc, wchar_t **argv)
477
478 The main program for the standard interpreter, encapsulating a full
479 initialization/finalization cycle, as well as additional
480 behaviour to implement reading configurations settings from the environment
481 and command line, and then executing ``__main__`` in accordance with
482 :ref:`using-on-cmdline`.
483
484 This is made available for programs which wish to support the full CPython
485 command line interface, rather than just embedding a Python runtime in a
486 larger application.
487
488 The *argc* and *argv* parameters are similar to those which are passed to a
489 C program's :c:func:`main` function, except that the *argv* entries are first
490 converted to ``wchar_t`` using :c:func:`Py_DecodeLocale`. It is also
491 important to note that the argument list entries may be modified to point to
492 strings other than those passed in (however, the contents of the strings
493 pointed to by the argument list are not modified).
494
495 The return value is ``2`` if the argument list does not represent a valid
496 Python command line, and otherwise the same as :c:func:`Py_RunMain`.
497
498 In terms of the CPython runtime configuration APIs documented in the
499 :ref:`runtime configuration <init-config>` section (and without accounting
500 for error handling), ``Py_Main`` is approximately equivalent to::
501
502 PyConfig config;
503 PyConfig_InitPythonConfig(&config);
504 PyConfig_SetArgv(&config, argc, argv);
505 Py_InitializeFromConfig(&config);
506 PyConfig_Clear(&config);
507
508 Py_RunMain();
509
510 In normal usage, an embedding application will call this function
511 *instead* of calling :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` or
512 :c:func:`Py_InitializeFromConfig` directly, and all settings will be applied
513 as described elsewhere in this documentation. If this function is instead
514 called *after* a preceding runtime initialization API call, then exactly
515 which environmental and command line configuration settings will be updated
516 is version dependent (as it depends on which settings correctly support
517 being modified after they have already been set once when the runtime was
518 first initialized).
519
520
521 .. c:function:: int Py_RunMain(void)
522
523 Executes the main module in a fully configured CPython runtime.
524
525 Executes the command (:c:member:`PyConfig.run_command`), the script
526 (:c:member:`PyConfig.run_filename`) or the module
527 (:c:member:`PyConfig.run_module`) specified on the command line or in the
528 configuration. If none of these values are set, runs the interactive Python
529 prompt (REPL) using the ``__main__`` module's global namespace.
530
531 If :c:member:`PyConfig.inspect` is not set (the default), the return value
532 will be ``0`` if the interpreter exits normally (that is, without raising
533 an exception), the exit status of an unhandled :exc:`SystemExit`, or ``1``
534 for any other unhandled exception.
535
536 If :c:member:`PyConfig.inspect` is set (such as when the :option:`-i` option
537 is used), rather than returning when the interpreter exits, execution will
538 instead resume in an interactive Python prompt (REPL) using the ``__main__``
539 module's global namespace. If the interpreter exited with an exception, it
540 is immediately raised in the REPL session. The function return value is
541 then determined by the way the *REPL session* terminates: ``0``, ``1``, or
542 the status of a :exc:`SystemExit`, as specified above.
543
544 This function always finalizes the Python interpreter before it returns.
545
546 See :ref:`Python Configuration <init-python-config>` for an example of a
547 customized Python that always runs in isolated mode using
548 :c:func:`Py_RunMain`.
549
550 .. c:function:: int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void *), void *data)
551
552 Register an :mod:`atexit` callback for the target interpreter *interp*.
553 This is similar to :c:func:`Py_AtExit`, but takes an explicit interpreter and
554 data pointer for the callback.
555
556 The :term:`GIL` must be held for *interp*.
557
558 .. versionadded:: 3.13
559
560 Process-wide parameters
561 =======================
562
563
564 .. c:function:: void Py_SetProgramName(const wchar_t *name)
565
566 .. index::
567 single: Py_Initialize()
568 single: main()
569 single: Py_GetPath()
570
571 This API is kept for backward compatibility: setting
572 :c:member:`PyConfig.program_name` should be used instead, see :ref:`Python
573 Initialization Configuration <init-config>`.
574
575 This function should be called before :c:func:`Py_Initialize` is called for
576 the first time, if it is called at all. It tells the interpreter the value
577 of the ``argv[0]`` argument to the :c:func:`main` function of the program
578 (converted to wide characters).
579 This is used by :c:func:`Py_GetPath` and some other functions below to find
580 the Python run-time libraries relative to the interpreter executable. The
581 default value is ``'python'``. The argument should point to a
582 zero-terminated wide character string in static storage whose contents will not
583 change for the duration of the program's execution. No code in the Python
584 interpreter will change the contents of this storage.
585
586 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
587 :c:expr:`wchar_t*` string.
588
589 .. deprecated:: 3.11
590
591
592 .. c:function:: wchar_t* Py_GetProgramName()
593
594 Return the program name set with :c:member:`PyConfig.program_name`, or the default.
595 The returned string points into static storage; the caller should not modify its
596 value.
597
598 This function should not be called before :c:func:`Py_Initialize`, otherwise
599 it returns ``NULL``.
600
601 .. versionchanged:: 3.10
602 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
603
604 .. deprecated-removed:: 3.13 3.15
605 Get :data:`sys.executable` instead.
606
607
608 .. c:function:: wchar_t* Py_GetPrefix()
609
610 Return the *prefix* for installed platform-independent files. This is derived
611 through a number of complicated rules from the program name set with
612 :c:member:`PyConfig.program_name` and some environment variables; for example, if the
613 program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
614 returned string points into static storage; the caller should not modify its
615 value. This corresponds to the :makevar:`prefix` variable in the top-level
616 :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
617 script at build time. The value is available to Python code as ``sys.base_prefix``.
618 It is only useful on Unix. See also the next function.
619
620 This function should not be called before :c:func:`Py_Initialize`, otherwise
621 it returns ``NULL``.
622
623 .. versionchanged:: 3.10
624 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
625
626 .. deprecated-removed:: 3.13 3.15
627 Get :data:`sys.base_prefix` instead, or :data:`sys.prefix` if
628 :ref:`virtual environments <venv-def>` need to be handled.
629
630
631 .. c:function:: wchar_t* Py_GetExecPrefix()
632
633 Return the *exec-prefix* for installed platform-*dependent* files. This is
634 derived through a number of complicated rules from the program name set with
635 :c:member:`PyConfig.program_name` and some environment variables; for example, if the
636 program name is ``'/usr/local/bin/python'``, the exec-prefix is
637 ``'/usr/local'``. The returned string points into static storage; the caller
638 should not modify its value. This corresponds to the :makevar:`exec_prefix`
639 variable in the top-level :file:`Makefile` and the ``--exec-prefix``
640 argument to the :program:`configure` script at build time. The value is
641 available to Python code as ``sys.base_exec_prefix``. It is only useful on
642 Unix.
643
644 Background: The exec-prefix differs from the prefix when platform dependent
645 files (such as executables and shared libraries) are installed in a different
646 directory tree. In a typical installation, platform dependent files may be
647 installed in the :file:`/usr/local/plat` subtree while platform independent may
648 be installed in :file:`/usr/local`.
649
650 Generally speaking, a platform is a combination of hardware and software
651 families, e.g. Sparc machines running the Solaris 2.x operating system are
652 considered the same platform, but Intel machines running Solaris 2.x are another
653 platform, and Intel machines running Linux are yet another platform. Different
654 major revisions of the same operating system generally also form different
655 platforms. Non-Unix operating systems are a different story; the installation
656 strategies on those systems are so different that the prefix and exec-prefix are
657 meaningless, and set to the empty string. Note that compiled Python bytecode
658 files are platform independent (but not independent from the Python version by
659 which they were compiled!).
660
661 System administrators will know how to configure the :program:`mount` or
662 :program:`automount` programs to share :file:`/usr/local` between platforms
663 while having :file:`/usr/local/plat` be a different filesystem for each
664 platform.
665
666 This function should not be called before :c:func:`Py_Initialize`, otherwise
667 it returns ``NULL``.
668
669 .. versionchanged:: 3.10
670 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
671
672 .. deprecated-removed:: 3.13 3.15
673 Get :data:`sys.base_exec_prefix` instead, or :data:`sys.exec_prefix` if
674 :ref:`virtual environments <venv-def>` need to be handled.
675
676
677 .. c:function:: wchar_t* Py_GetProgramFullPath()
678
679 .. index::
680 single: executable (in module sys)
681
682 Return the full program name of the Python executable; this is computed as a
683 side-effect of deriving the default module search path from the program name
684 (set by :c:member:`PyConfig.program_name`). The returned string points into
685 static storage; the caller should not modify its value. The value is available
686 to Python code as ``sys.executable``.
687
688 This function should not be called before :c:func:`Py_Initialize`, otherwise
689 it returns ``NULL``.
690
691 .. versionchanged:: 3.10
692 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
693
694 .. deprecated-removed:: 3.13 3.15
695 Get :data:`sys.executable` instead.
696
697
698 .. c:function:: wchar_t* Py_GetPath()
699
700 .. index::
701 triple: module; search; path
702 single: path (in module sys)
703
704 Return the default module search path; this is computed from the program name
705 (set by :c:member:`PyConfig.program_name`) and some environment variables.
706 The returned string consists of a series of directory names separated by a
707 platform dependent delimiter character. The delimiter character is ``':'``
708 on Unix and macOS, ``';'`` on Windows. The returned string points into
709 static storage; the caller should not modify its value. The list
710 :data:`sys.path` is initialized with this value on interpreter startup; it
711 can be (and usually is) modified later to change the search path for loading
712 modules.
713
714 This function should not be called before :c:func:`Py_Initialize`, otherwise
715 it returns ``NULL``.
716
717 .. XXX should give the exact rules
718
719 .. versionchanged:: 3.10
720 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
721
722 .. deprecated-removed:: 3.13 3.15
723 Get :data:`sys.path` instead.
724
725
726 .. c:function:: const char* Py_GetVersion()
727
728 Return the version of this Python interpreter. This is a string that looks
729 something like ::
730
731 "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
732
733 .. index:: single: version (in module sys)
734
735 The first word (up to the first space character) is the current Python version;
736 the first characters are the major and minor version separated by a
737 period. The returned string points into static storage; the caller should not
738 modify its value. The value is available to Python code as :data:`sys.version`.
739
740 See also the :c:var:`Py_Version` constant.
741
742
743 .. c:function:: const char* Py_GetPlatform()
744
745 .. index:: single: platform (in module sys)
746
747 Return the platform identifier for the current platform. On Unix, this is
748 formed from the "official" name of the operating system, converted to lower
749 case, followed by the major revision number; e.g., for Solaris 2.x, which is
750 also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is
751 ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
752 static storage; the caller should not modify its value. The value is available
753 to Python code as ``sys.platform``.
754
755
756 .. c:function:: const char* Py_GetCopyright()
757
758 Return the official copyright string for the current Python version, for example
759
760 ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
761
762 .. index:: single: copyright (in module sys)
763
764 The returned string points into static storage; the caller should not modify its
765 value. The value is available to Python code as ``sys.copyright``.
766
767
768 .. c:function:: const char* Py_GetCompiler()
769
770 Return an indication of the compiler used to build the current Python version,
771 in square brackets, for example::
772
773 "[GCC 2.7.2.2]"
774
775 .. index:: single: version (in module sys)
776
777 The returned string points into static storage; the caller should not modify its
778 value. The value is available to Python code as part of the variable
779 ``sys.version``.
780
781
782 .. c:function:: const char* Py_GetBuildInfo()
783
784 Return information about the sequence number and build date and time of the
785 current Python interpreter instance, for example ::
786
787 "#67, Aug 1 1997, 22:34:28"
788
789 .. index:: single: version (in module sys)
790
791 The returned string points into static storage; the caller should not modify its
792 value. The value is available to Python code as part of the variable
793 ``sys.version``.
794
795
796 .. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
797
798 .. index::
799 single: main()
800 single: Py_FatalError()
801 single: argv (in module sys)
802
803 This API is kept for backward compatibility: setting
804 :c:member:`PyConfig.argv`, :c:member:`PyConfig.parse_argv` and
805 :c:member:`PyConfig.safe_path` should be used instead, see :ref:`Python
806 Initialization Configuration <init-config>`.
807
808 Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
809 similar to those passed to the program's :c:func:`main` function with the
810 difference that the first entry should refer to the script file to be
811 executed rather than the executable hosting the Python interpreter. If there
812 isn't a script that will be run, the first entry in *argv* can be an empty
813 string. If this function fails to initialize :data:`sys.argv`, a fatal
814 condition is signalled using :c:func:`Py_FatalError`.
815
816 If *updatepath* is zero, this is all the function does. If *updatepath*
817 is non-zero, the function also modifies :data:`sys.path` according to the
818 following algorithm:
819
820 - If the name of an existing script is passed in ``argv[0]``, the absolute
821 path of the directory where the script is located is prepended to
822 :data:`sys.path`.
823 - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
824 to an existing file name), an empty string is prepended to
825 :data:`sys.path`, which is the same as prepending the current working
826 directory (``"."``).
827
828 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
829 :c:expr:`wchar_t*` string.
830
831 See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
832 members of the :ref:`Python Initialization Configuration <init-config>`.
833
834 .. note::
835 It is recommended that applications embedding the Python interpreter
836 for purposes other than executing a single script pass ``0`` as *updatepath*,
837 and update :data:`sys.path` themselves if desired.
838 See :cve:`2008-5983`.
839
840 On versions before 3.1.3, you can achieve the same effect by manually
841 popping the first :data:`sys.path` element after having called
842 :c:func:`PySys_SetArgv`, for example using::
843
844 PyRun_SimpleString("import sys; sys.path.pop(0)\n");
845
846 .. versionadded:: 3.1.3
847
848 .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
849 check w/ Guido.
850
851 .. deprecated:: 3.11
852
853
854 .. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
855
856 This API is kept for backward compatibility: setting
857 :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` should be used
858 instead, see :ref:`Python Initialization Configuration <init-config>`.
859
860 This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
861 to ``1`` unless the :program:`python` interpreter was started with the
862 :option:`-I`.
863
864 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
865 :c:expr:`wchar_t*` string.
866
867 See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
868 members of the :ref:`Python Initialization Configuration <init-config>`.
869
870 .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
871
872 .. deprecated:: 3.11
873
874
875 .. c:function:: void Py_SetPythonHome(const wchar_t *home)
876
877 This API is kept for backward compatibility: setting
878 :c:member:`PyConfig.home` should be used instead, see :ref:`Python
879 Initialization Configuration <init-config>`.
880
881 Set the default "home" directory, that is, the location of the standard
882 Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
883 argument string.
884
885 The argument should point to a zero-terminated character string in static
886 storage whose contents will not change for the duration of the program's
887 execution. No code in the Python interpreter will change the contents of
888 this storage.
889
890 Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
891 :c:expr:`wchar_t*` string.
892
893 .. deprecated:: 3.11
894
895
896 .. c:function:: wchar_t* Py_GetPythonHome()
897
898 Return the default "home", that is, the value set by
899 :c:member:`PyConfig.home`, or the value of the :envvar:`PYTHONHOME`
900 environment variable if it is set.
901
902 This function should not be called before :c:func:`Py_Initialize`, otherwise
903 it returns ``NULL``.
904
905 .. versionchanged:: 3.10
906 It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
907
908 .. deprecated-removed:: 3.13 3.15
909 Get :c:member:`PyConfig.home` or :envvar:`PYTHONHOME` environment
910 variable instead.
911
912
913 .. _threads:
914
915 Thread State and the Global Interpreter Lock
916 ============================================
917
918 .. index::
919 single: global interpreter lock
920 single: interpreter lock
921 single: lock, interpreter
922
923 The Python interpreter is not fully thread-safe. In order to support
924 multi-threaded Python programs, there's a global lock, called the :term:`global
925 interpreter lock` or :term:`GIL`, that must be held by the current thread before
926 it can safely access Python objects. Without the lock, even the simplest
927 operations could cause problems in a multi-threaded program: for example, when
928 two threads simultaneously increment the reference count of the same object, the
929 reference count could end up being incremented only once instead of twice.
930
931 .. index:: single: setswitchinterval (in module sys)
932
933 Therefore, the rule exists that only the thread that has acquired the
934 :term:`GIL` may operate on Python objects or call Python/C API functions.
935 In order to emulate concurrency of execution, the interpreter regularly
936 tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also
937 released around potentially blocking I/O operations like reading or writing
938 a file, so that other Python threads can run in the meantime.
939
940 .. index::
941 single: PyThreadState (C type)
942
943 The Python interpreter keeps some thread-specific bookkeeping information
944 inside a data structure called :c:type:`PyThreadState`. There's also one
945 global variable pointing to the current :c:type:`PyThreadState`: it can
946 be retrieved using :c:func:`PyThreadState_Get`.
947
948 Releasing the GIL from extension code
949 -------------------------------------
950
951 Most extension code manipulating the :term:`GIL` has the following simple
952 structure::
953
954 Save the thread state in a local variable.
955 Release the global interpreter lock.
956 ... Do some blocking I/O operation ...
957 Reacquire the global interpreter lock.
958 Restore the thread state from the local variable.
959
960 This is so common that a pair of macros exists to simplify it::
961
962 Py_BEGIN_ALLOW_THREADS
963 ... Do some blocking I/O operation ...
964 Py_END_ALLOW_THREADS
965
966 .. index::
967 single: Py_BEGIN_ALLOW_THREADS (C macro)
968 single: Py_END_ALLOW_THREADS (C macro)
969
970 The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
971 hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
972 block.
973
974 The block above expands to the following code::
975
976 PyThreadState *_save;
977
978 _save = PyEval_SaveThread();
979 ... Do some blocking I/O operation ...
980 PyEval_RestoreThread(_save);
981
982 .. index::
983 single: PyEval_RestoreThread (C function)
984 single: PyEval_SaveThread (C function)
985
986 Here is how these functions work: the global interpreter lock is used to protect the pointer to the
987 current thread state. When releasing the lock and saving the thread state,
988 the current thread state pointer must be retrieved before the lock is released
989 (since another thread could immediately acquire the lock and store its own thread
990 state in the global variable). Conversely, when acquiring the lock and restoring
991 the thread state, the lock must be acquired before storing the thread state
992 pointer.
993
994 .. note::
995 Calling system I/O functions is the most common use case for releasing
996 the GIL, but it can also be useful before calling long-running computations
997 which don't need access to Python objects, such as compression or
998 cryptographic functions operating over memory buffers. For example, the
999 standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
1000 compressing or hashing data.
1001
1002
1003 .. _gilstate:
1004
1005 Non-Python created threads
1006 --------------------------
1007
1008 When threads are created using the dedicated Python APIs (such as the
1009 :mod:`threading` module), a thread state is automatically associated to them
1010 and the code showed above is therefore correct. However, when threads are
1011 created from C (for example by a third-party library with its own thread
1012 management), they don't hold the GIL, nor is there a thread state structure
1013 for them.
1014
1015 If you need to call Python code from these threads (often this will be part
1016 of a callback API provided by the aforementioned third-party library),
1017 you must first register these threads with the interpreter by
1018 creating a thread state data structure, then acquiring the GIL, and finally
1019 storing their thread state pointer, before you can start using the Python/C
1020 API. When you are done, you should reset the thread state pointer, release
1021 the GIL, and finally free the thread state data structure.
1022
1023 The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
1024 all of the above automatically. The typical idiom for calling into Python
1025 from a C thread is::
1026
1027 PyGILState_STATE gstate;
1028 gstate = PyGILState_Ensure();
1029
1030 /* Perform Python actions here. */
1031 result = CallSomeFunction();
1032 /* evaluate result or handle exception */
1033
1034 /* Release the thread. No Python API allowed beyond this point. */
1035 PyGILState_Release(gstate);
1036
1037 Note that the ``PyGILState_*`` functions assume there is only one global
1038 interpreter (created automatically by :c:func:`Py_Initialize`). Python
1039 supports the creation of additional interpreters (using
1040 :c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
1041 ``PyGILState_*`` API is unsupported.
1042
1043
1044 .. _fork-and-threads:
1045
1046 Cautions about fork()
1047 ---------------------
1048
1049 Another important thing to note about threads is their behaviour in the face
1050 of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
1051 process forks only the thread that issued the fork will exist. This has a
1052 concrete impact both on how locks must be handled and on all stored state
1053 in CPython's runtime.
1054
1055 The fact that only the "current" thread remains
1056 means any locks held by other threads will never be released. Python solves
1057 this for :func:`os.fork` by acquiring the locks it uses internally before
1058 the fork, and releasing them afterwards. In addition, it resets any
1059 :ref:`lock-objects` in the child. When extending or embedding Python, there
1060 is no way to inform Python of additional (non-Python) locks that need to be
1061 acquired before or reset after a fork. OS facilities such as
1062 :c:func:`!pthread_atfork` would need to be used to accomplish the same thing.
1063 Additionally, when extending or embedding Python, calling :c:func:`fork`
1064 directly rather than through :func:`os.fork` (and returning to or calling
1065 into Python) may result in a deadlock by one of Python's internal locks
1066 being held by a thread that is defunct after the fork.
1067 :c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
1068 always able to.
1069
1070 The fact that all other threads go away also means that CPython's
1071 runtime state there must be cleaned up properly, which :func:`os.fork`
1072 does. This means finalizing all other :c:type:`PyThreadState` objects
1073 belonging to the current interpreter and all other
1074 :c:type:`PyInterpreterState` objects. Due to this and the special
1075 nature of the :ref:`"main" interpreter <sub-interpreter-support>`,
1076 :c:func:`fork` should only be called in that interpreter's "main"
1077 thread, where the CPython global runtime was originally initialized.
1078 The only exception is if :c:func:`exec` will be called immediately
1079 after.
1080
1081 .. _cautions-regarding-runtime-finalization:
1082
1083 Cautions regarding runtime finalization
1084 ---------------------------------------
1085
1086 In the late stage of :term:`interpreter shutdown`, after attempting to wait for
1087 non-daemon threads to exit (though this can be interrupted by
1088 :class:`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime
1089 is marked as *finalizing*: :c:func:`Py_IsFinalizing` and
1090 :func:`sys.is_finalizing` return true. At this point, only the *finalization
1091 thread* that initiated finalization (typically the main thread) is allowed to
1092 acquire the :term:`GIL`.
1093
1094 If any thread, other than the finalization thread, attempts to acquire the GIL
1095 during finalization, either explicitly via :c:func:`PyGILState_Ensure`,
1096 :c:macro:`Py_END_ALLOW_THREADS`, :c:func:`PyEval_AcquireThread`, or
1097 :c:func:`!PyEval_AcquireLock`, or implicitly when the interpreter attempts to
1098 reacquire it after having yielded it, the thread enters **a permanently blocked
1099 state** where it remains until the program exits. In most cases this is
1100 harmless, but this can result in deadlock if a later stage of finalization
1101 attempts to acquire a lock owned by the blocked thread, or otherwise waits on
1102 the blocked thread.
1103
1104 Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++
1105 finalizations further up the call stack when such threads were forcibly exited
1106 here in CPython 3.13.7 and earlier. The CPython runtime GIL acquiring C APIs
1107 have never had any error reporting or handling expectations at GIL acquisition
1108 time that would've allowed for graceful exit from this situation. Changing that
1109 would require new stable C APIs and rewriting the majority of C code in the
1110 CPython ecosystem to use those with error handling.
1111
1112
1113 High-level API
1114 --------------
1115
1116 These are the most commonly used types and functions when writing C extension
1117 code, or when embedding the Python interpreter:
1118
1119 .. c:type:: PyInterpreterState
1120
1121 This data structure represents the state shared by a number of cooperating
1122 threads. Threads belonging to the same interpreter share their module
1123 administration and a few other internal items. There are no public members in
1124 this structure.
1125
1126 Threads belonging to different interpreters initially share nothing, except
1127 process state like available memory, open file descriptors and such. The global
1128 interpreter lock is also shared by all threads, regardless of to which
1129 interpreter they belong.
1130
1131 .. versionchanged:: 3.12
1132
1133 :pep:`684` introduced the possibility
1134 of a :ref:`per-interpreter GIL <per-interpreter-gil>`.
1135 See :c:func:`Py_NewInterpreterFromConfig`.
1136
1137
1138 .. c:type:: PyThreadState
1139
1140 This data structure represents the state of a single thread. The only public
1141 data member is:
1142
1143 .. c:member:: PyInterpreterState *interp
1144
1145 This thread's interpreter state.
1146
1147
1148 .. c:function:: void PyEval_InitThreads()
1149
1150 .. index::
1151 single: PyEval_AcquireThread()
1152 single: PyEval_ReleaseThread()
1153 single: PyEval_SaveThread()
1154 single: PyEval_RestoreThread()
1155
1156 Deprecated function which does nothing.
1157
1158 In Python 3.6 and older, this function created the GIL if it didn't exist.
1159
1160 .. versionchanged:: 3.9
1161 The function now does nothing.
1162
1163 .. versionchanged:: 3.7
1164 This function is now called by :c:func:`Py_Initialize()`, so you don't
1165 have to call it yourself anymore.
1166
1167 .. versionchanged:: 3.2
1168 This function cannot be called before :c:func:`Py_Initialize()` anymore.
1169
1170 .. deprecated:: 3.9
1171
1172 .. index:: pair: module; _thread
1173
1174
1175 .. c:function:: PyThreadState* PyEval_SaveThread()
1176
1177 Release the global interpreter lock (if it has been created) and reset the
1178 thread state to ``NULL``, returning the previous thread state (which is not
1179 ``NULL``). If the lock has been created, the current thread must have
1180 acquired it.
1181
1182
1183 .. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
1184
1185 Acquire the global interpreter lock (if it has been created) and set the
1186 thread state to *tstate*, which must not be ``NULL``. If the lock has been
1187 created, the current thread must not have acquired it, otherwise deadlock
1188 ensues.
1189
1190 .. note::
1191 Calling this function from a thread when the runtime is finalizing will
1192 hang the thread until the program exits, even if the thread was not
1193 created by Python. Refer to
1194 :ref:`cautions-regarding-runtime-finalization` for more details.
1195
1196 .. versionchanged:: 3.13.8
1197 Hangs the current thread, rather than terminating it, if called while the
1198 interpreter is finalizing.
1199
1200 .. c:function:: PyThreadState* PyThreadState_Get()
1201
1202 Return the current thread state. The global interpreter lock must be held.
1203 When the current thread state is ``NULL``, this issues a fatal error (so that
1204 the caller needn't check for ``NULL``).
1205
1206 See also :c:func:`PyThreadState_GetUnchecked`.
1207
1208
1209 .. c:function:: PyThreadState* PyThreadState_GetUnchecked()
1210
1211 Similar to :c:func:`PyThreadState_Get`, but don't kill the process with a
1212 fatal error if it is NULL. The caller is responsible to check if the result
1213 is NULL.
1214
1215 .. versionadded:: 3.13
1216 In Python 3.5 to 3.12, the function was private and known as
1217 ``_PyThreadState_UncheckedGet()``.
1218
1219
1220 .. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
1221
1222 Swap the current thread state with the thread state given by the argument
1223 *tstate*, which may be ``NULL``.
1224
1225 The :term:`GIL` does not need to be held, but will be held upon returning
1226 if *tstate* is non-``NULL``.
1227
1228 The following functions use thread-local storage, and are not compatible
1229 with sub-interpreters:
1230
1231 .. c:type:: PyGILState_STATE
1232
1233 The type of the value returned by :c:func:`PyGILState_Ensure` and passed to
1234 :c:func:`PyGILState_Release`.
1235
1236 .. c:enumerator:: PyGILState_LOCKED
1237
1238 The GIL was already held when :c:func:`PyGILState_Ensure` was called.
1239
1240 .. c:enumerator:: PyGILState_UNLOCKED
1241
1242 The GIL was not held when :c:func:`PyGILState_Ensure` was called.
1243
1244 .. c:function:: PyGILState_STATE PyGILState_Ensure()
1245
1246 Ensure that the current thread is ready to call the Python C API regardless
1247 of the current state of Python, or of the global interpreter lock. This may
1248 be called as many times as desired by a thread as long as each call is
1249 matched with a call to :c:func:`PyGILState_Release`. In general, other
1250 thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
1251 :c:func:`PyGILState_Release` calls as long as the thread state is restored to
1252 its previous state before the Release(). For example, normal usage of the
1253 :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
1254 acceptable.
1255
1256 The return value is an opaque "handle" to the thread state when
1257 :c:func:`PyGILState_Ensure` was called, and must be passed to
1258 :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
1259 though recursive calls are allowed, these handles *cannot* be shared - each
1260 unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
1261 to :c:func:`PyGILState_Release`.
1262
1263 When the function returns, the current thread will hold the GIL and be able
1264 to call arbitrary Python code. Failure is a fatal error.
1265
1266 .. note::
1267 Calling this function from a thread when the runtime is finalizing will
1268 hang the thread until the program exits, even if the thread was not
1269 created by Python. Refer to
1270 :ref:`cautions-regarding-runtime-finalization` for more details.
1271
1272 .. versionchanged:: 3.13.8
1273 Hangs the current thread, rather than terminating it, if called while the
1274 interpreter is finalizing.
1275
1276 .. c:function:: void PyGILState_Release(PyGILState_STATE)
1277
1278 Release any resources previously acquired. After this call, Python's state will
1279 be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
1280 (but generally this state will be unknown to the caller, hence the use of the
1281 GILState API).
1282
1283 Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
1284 :c:func:`PyGILState_Release` on the same thread.
1285
1286
1287 .. c:function:: PyThreadState* PyGILState_GetThisThreadState()
1288
1289 Get the current thread state for this thread. May return ``NULL`` if no
1290 GILState API has been used on the current thread. Note that the main thread
1291 always has such a thread-state, even if no auto-thread-state call has been
1292 made on the main thread. This is mainly a helper/diagnostic function.
1293
1294
1295 .. c:function:: int PyGILState_Check()
1296
1297 Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
1298 This function can be called from any thread at any time.
1299 Only if it has had its Python thread state initialized and currently is
1300 holding the GIL will it return ``1``.
1301 This is mainly a helper/diagnostic function. It can be useful
1302 for example in callback contexts or memory allocation functions when
1303 knowing that the GIL is locked can allow the caller to perform sensitive
1304 actions or otherwise behave differently.
1305
1306 .. versionadded:: 3.4
1307
1308
1309 The following macros are normally used without a trailing semicolon; look for
1310 example usage in the Python source distribution.
1311
1312
1313 .. c:macro:: Py_BEGIN_ALLOW_THREADS
1314
1315 This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
1316 Note that it contains an opening brace; it must be matched with a following
1317 :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
1318 macro.
1319
1320
1321 .. c:macro:: Py_END_ALLOW_THREADS
1322
1323 This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
1324 a closing brace; it must be matched with an earlier
1325 :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
1326 this macro.
1327
1328
1329 .. c:macro:: Py_BLOCK_THREADS
1330
1331 This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
1332 :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
1333
1334
1335 .. c:macro:: Py_UNBLOCK_THREADS
1336
1337 This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
1338 :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
1339 declaration.
1340
1341
1342 Low-level API
1343 -------------
1344
1345 All of the following functions must be called after :c:func:`Py_Initialize`.
1346
1347 .. versionchanged:: 3.7
1348 :c:func:`Py_Initialize()` now initializes the :term:`GIL`.
1349
1350
1351 .. c:function:: PyInterpreterState* PyInterpreterState_New()
1352
1353 Create a new interpreter state object. The global interpreter lock need not
1354 be held, but may be held if it is necessary to serialize calls to this
1355 function.
1356
1357 .. audit-event:: cpython.PyInterpreterState_New "" c.PyInterpreterState_New
1358
1359
1360 .. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
1361
1362 Reset all information in an interpreter state object. The global interpreter
1363 lock must be held.
1364
1365 .. audit-event:: cpython.PyInterpreterState_Clear "" c.PyInterpreterState_Clear
1366
1367
1368 .. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
1369
1370 Destroy an interpreter state object. The global interpreter lock need not be
1371 held. The interpreter state must have been reset with a previous call to
1372 :c:func:`PyInterpreterState_Clear`.
1373
1374
1375 .. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
1376
1377 Create a new thread state object belonging to the given interpreter object.
1378 The global interpreter lock need not be held, but may be held if it is
1379 necessary to serialize calls to this function.
1380
1381
1382 .. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
1383
1384 Reset all information in a thread state object. The global interpreter lock
1385 must be held.
1386
1387 .. versionchanged:: 3.9
1388 This function now calls the :c:member:`!PyThreadState.on_delete` callback.
1389 Previously, that happened in :c:func:`PyThreadState_Delete`.
1390
1391 .. versionchanged:: 3.13
1392 The :c:member:`!PyThreadState.on_delete` callback was removed.
1393
1394
1395 .. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
1396
1397 Destroy a thread state object. The global interpreter lock need not be held.
1398 The thread state must have been reset with a previous call to
1399 :c:func:`PyThreadState_Clear`.
1400
1401
1402 .. c:function:: void PyThreadState_DeleteCurrent(void)
1403
1404 Destroy the current thread state and release the global interpreter lock.
1405 Like :c:func:`PyThreadState_Delete`, the global interpreter lock must
1406 be held. The thread state must have been reset with a previous call
1407 to :c:func:`PyThreadState_Clear`.
1408
1409
1410 .. c:function:: PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
1411
1412 Get the current frame of the Python thread state *tstate*.
1413
1414 Return a :term:`strong reference`. Return ``NULL`` if no frame is currently
1415 executing.
1416
1417 See also :c:func:`PyEval_GetFrame`.
1418
1419 *tstate* must not be ``NULL``.
1420
1421 .. versionadded:: 3.9
1422
1423
1424 .. c:function:: uint64_t PyThreadState_GetID(PyThreadState *tstate)
1425
1426 Get the unique thread state identifier of the Python thread state *tstate*.
1427
1428 *tstate* must not be ``NULL``.
1429
1430 .. versionadded:: 3.9
1431
1432
1433 .. c:function:: PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState *tstate)
1434
1435 Get the interpreter of the Python thread state *tstate*.
1436
1437 *tstate* must not be ``NULL``.
1438
1439 .. versionadded:: 3.9
1440
1441
1442 .. c:function:: void PyThreadState_EnterTracing(PyThreadState *tstate)
1443
1444 Suspend tracing and profiling in the Python thread state *tstate*.
1445
1446 Resume them using the :c:func:`PyThreadState_LeaveTracing` function.
1447
1448 .. versionadded:: 3.11
1449
1450
1451 .. c:function:: void PyThreadState_LeaveTracing(PyThreadState *tstate)
1452
1453 Resume tracing and profiling in the Python thread state *tstate* suspended
1454 by the :c:func:`PyThreadState_EnterTracing` function.
1455
1456 See also :c:func:`PyEval_SetTrace` and :c:func:`PyEval_SetProfile`
1457 functions.
1458
1459 .. versionadded:: 3.11
1460
1461
1462 .. c:function:: PyInterpreterState* PyInterpreterState_Get(void)
1463
1464 Get the current interpreter.
1465
1466 Issue a fatal error if there no current Python thread state or no current
1467 interpreter. It cannot return NULL.
1468
1469 The caller must hold the GIL.
1470
1471 .. versionadded:: 3.9
1472
1473
1474 .. c:function:: int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
1475
1476 Return the interpreter's unique ID. If there was any error in doing
1477 so then ``-1`` is returned and an error is set.
1478
1479 The caller must hold the GIL.
1480
1481 .. versionadded:: 3.7
1482
1483
1484 .. c:function:: PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp)
1485
1486 Return a dictionary in which interpreter-specific data may be stored.
1487 If this function returns ``NULL`` then no exception has been raised and
1488 the caller should assume no interpreter-specific dict is available.
1489
1490 This is not a replacement for :c:func:`PyModule_GetState()`, which
1491 extensions should use to store interpreter-specific state information.
1492
1493 The returned dictionary is borrowed from the interpreter and is valid until
1494 interpreter shutdown.
1495
1496 .. versionadded:: 3.8
1497
1498
1499 .. c:function:: PyObject* PyUnstable_InterpreterState_GetMainModule(PyInterpreterState *interp)
1500
1501 Return a :term:`strong reference` to the ``__main__`` :ref:`module object <moduleobjects>`
1502 for the given interpreter.
1503
1504 The caller must hold the GIL.
1505
1506 .. versionadded:: 3.13
1507
1508
1509 .. c:type:: PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
1510
1511 Type of a frame evaluation function.
1512
1513 The *throwflag* parameter is used by the ``throw()`` method of generators:
1514 if non-zero, handle the current exception.
1515
1516 .. versionchanged:: 3.9
1517 The function now takes a *tstate* parameter.
1518
1519 .. versionchanged:: 3.11
1520 The *frame* parameter changed from ``PyFrameObject*`` to ``_PyInterpreterFrame*``.
1521
1522 .. c:function:: _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1523
1524 Get the frame evaluation function.
1525
1526 See the :pep:`523` "Adding a frame evaluation API to CPython".
1527
1528 .. versionadded:: 3.9
1529
1530 .. c:function:: void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)
1531
1532 Set the frame evaluation function.
1533
1534 See the :pep:`523` "Adding a frame evaluation API to CPython".
1535
1536 .. versionadded:: 3.9
1537
1538
1539 .. c:function:: PyObject* PyThreadState_GetDict()
1540
1541 Return a dictionary in which extensions can store thread-specific state
1542 information. Each extension should use a unique key to use to store state in
1543 the dictionary. It is okay to call this function when no current thread state
1544 is available. If this function returns ``NULL``, no exception has been raised and
1545 the caller should assume no current thread state is available.
1546
1547
1548 .. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1549
1550 Asynchronously raise an exception in a thread. The *id* argument is the thread
1551 id of the target thread; *exc* is the exception object to be raised. This
1552 function does not steal any references to *exc*. To prevent naive misuse, you
1553 must write your own C extension to call this. Must be called with the GIL held.
1554 Returns the number of thread states modified; this is normally one, but will be
1555 zero if the thread id isn't found. If *exc* is ``NULL``, the pending
1556 exception (if any) for the thread is cleared. This raises no exceptions.
1557
1558 .. versionchanged:: 3.7
1559 The type of the *id* parameter changed from :c:expr:`long` to
1560 :c:expr:`unsigned long`.
1561
1562 .. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
1563
1564 Acquire the global interpreter lock and set the current thread state to
1565 *tstate*, which must not be ``NULL``. The lock must have been created earlier.
1566 If this thread already has the lock, deadlock ensues.
1567
1568 .. note::
1569 Calling this function from a thread when the runtime is finalizing will
1570 hang the thread until the program exits, even if the thread was not
1571 created by Python. Refer to
1572 :ref:`cautions-regarding-runtime-finalization` for more details.
1573
1574 .. versionchanged:: 3.8
1575 Updated to be consistent with :c:func:`PyEval_RestoreThread`,
1576 :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
1577 and terminate the current thread if called while the interpreter is finalizing.
1578
1579 .. versionchanged:: 3.13.8
1580 Hangs the current thread, rather than terminating it, if called while the
1581 interpreter is finalizing.
1582
1583 :c:func:`PyEval_RestoreThread` is a higher-level function which is always
1584 available (even when threads have not been initialized).
1585
1586
1587 .. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
1588
1589 Reset the current thread state to ``NULL`` and release the global interpreter
1590 lock. The lock must have been created earlier and must be held by the current
1591 thread. The *tstate* argument, which must not be ``NULL``, is only used to check
1592 that it represents the current thread state --- if it isn't, a fatal error is
1593 reported.
1594
1595 :c:func:`PyEval_SaveThread` is a higher-level function which is always
1596 available (even when threads have not been initialized).
1597
1598
1599 .. _sub-interpreter-support:
1600
1601 Sub-interpreter support
1602 =======================
1603
1604 While in most uses, you will only embed a single Python interpreter, there
1605 are cases where you need to create several independent interpreters in the
1606 same process and perhaps even in the same thread. Sub-interpreters allow
1607 you to do that.
1608
1609 The "main" interpreter is the first one created when the runtime initializes.
1610 It is usually the only Python interpreter in a process. Unlike sub-interpreters,
1611 the main interpreter has unique process-global responsibilities like signal
1612 handling. It is also responsible for execution during runtime initialization and
1613 is usually the active interpreter during runtime finalization. The
1614 :c:func:`PyInterpreterState_Main` function returns a pointer to its state.
1615
1616 You can switch between sub-interpreters using the :c:func:`PyThreadState_Swap`
1617 function. You can create and destroy them using the following functions:
1618
1619
1620 .. c:type:: PyInterpreterConfig
1621
1622 Structure containing most parameters to configure a sub-interpreter.
1623 Its values are used only in :c:func:`Py_NewInterpreterFromConfig` and
1624 never modified by the runtime.
1625
1626 .. versionadded:: 3.12
1627
1628 Structure fields:
1629
1630 .. c:member:: int use_main_obmalloc
1631
1632 If this is ``0`` then the sub-interpreter will use its own
1633 "object" allocator state.
1634 Otherwise it will use (share) the main interpreter's.
1635
1636 If this is ``0`` then
1637 :c:member:`~PyInterpreterConfig.check_multi_interp_extensions`
1638 must be ``1`` (non-zero).
1639 If this is ``1`` then :c:member:`~PyInterpreterConfig.gil`
1640 must not be :c:macro:`PyInterpreterConfig_OWN_GIL`.
1641
1642 .. c:member:: int allow_fork
1643
1644 If this is ``0`` then the runtime will not support forking the
1645 process in any thread where the sub-interpreter is currently active.
1646 Otherwise fork is unrestricted.
1647
1648 Note that the :mod:`subprocess` module still works
1649 when fork is disallowed.
1650
1651 .. c:member:: int allow_exec
1652
1653 If this is ``0`` then the runtime will not support replacing the
1654 current process via exec (e.g. :func:`os.execv`) in any thread
1655 where the sub-interpreter is currently active.
1656 Otherwise exec is unrestricted.
1657
1658 Note that the :mod:`subprocess` module still works
1659 when exec is disallowed.
1660
1661 .. c:member:: int allow_threads
1662
1663 If this is ``0`` then the sub-interpreter's :mod:`threading` module
1664 won't create threads.
1665 Otherwise threads are allowed.
1666
1667 .. c:member:: int allow_daemon_threads
1668
1669 If this is ``0`` then the sub-interpreter's :mod:`threading` module
1670 won't create daemon threads.
1671 Otherwise daemon threads are allowed (as long as
1672 :c:member:`~PyInterpreterConfig.allow_threads` is non-zero).
1673
1674 .. c:member:: int check_multi_interp_extensions
1675
1676 If this is ``0`` then all extension modules may be imported,
1677 including legacy (single-phase init) modules,
1678 in any thread where the sub-interpreter is currently active.
1679 Otherwise only multi-phase init extension modules
1680 (see :pep:`489`) may be imported.
1681 (Also see :c:macro:`Py_mod_multiple_interpreters`.)
1682
1683 This must be ``1`` (non-zero) if
1684 :c:member:`~PyInterpreterConfig.use_main_obmalloc` is ``0``.
1685
1686 .. c:member:: int gil
1687
1688 This determines the operation of the GIL for the sub-interpreter.
1689 It may be one of the following:
1690
1691 .. c:namespace:: NULL
1692
1693 .. c:macro:: PyInterpreterConfig_DEFAULT_GIL
1694
1695 Use the default selection (:c:macro:`PyInterpreterConfig_SHARED_GIL`).
1696
1697 .. c:macro:: PyInterpreterConfig_SHARED_GIL
1698
1699 Use (share) the main interpreter's GIL.
1700
1701 .. c:macro:: PyInterpreterConfig_OWN_GIL
1702
1703 Use the sub-interpreter's own GIL.
1704
1705 If this is :c:macro:`PyInterpreterConfig_OWN_GIL` then
1706 :c:member:`PyInterpreterConfig.use_main_obmalloc` must be ``0``.
1707
1708
1709 .. c:function:: PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
1710
1711 .. index::
1712 pair: module; builtins
1713 pair: module; __main__
1714 pair: module; sys
1715 single: stdout (in module sys)
1716 single: stderr (in module sys)
1717 single: stdin (in module sys)
1718
1719 Create a new sub-interpreter. This is an (almost) totally separate environment
1720 for the execution of Python code. In particular, the new interpreter has
1721 separate, independent versions of all imported modules, including the
1722 fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
1723 table of loaded modules (``sys.modules``) and the module search path
1724 (``sys.path``) are also separate. The new environment has no ``sys.argv``
1725 variable. It has new standard I/O stream file objects ``sys.stdin``,
1726 ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
1727 file descriptors).
1728
1729 The given *config* controls the options with which the interpreter
1730 is initialized.
1731
1732 Upon success, *tstate_p* will be set to the first thread state
1733 created in the new
1734 sub-interpreter. This thread state is made in the current thread state.
1735 Note that no actual thread is created; see the discussion of thread states
1736 below. If creation of the new interpreter is unsuccessful,
1737 *tstate_p* is set to ``NULL``;
1738 no exception is set since the exception state is stored in the
1739 current thread state and there may not be a current thread state.
1740
1741 Like all other Python/C API functions, the global interpreter lock
1742 must be held before calling this function and is still held when it
1743 returns. Likewise a current thread state must be set on entry. On
1744 success, the returned thread state will be set as current. If the
1745 sub-interpreter is created with its own GIL then the GIL of the
1746 calling interpreter will be released. When the function returns,
1747 the new interpreter's GIL will be held by the current thread and
1748 the previously interpreter's GIL will remain released here.
1749
1750 .. versionadded:: 3.12
1751
1752 Sub-interpreters are most effective when isolated from each other,
1753 with certain functionality restricted::
1754
1755 PyInterpreterConfig config = {
1756 .use_main_obmalloc = 0,
1757 .allow_fork = 0,
1758 .allow_exec = 0,
1759 .allow_threads = 1,
1760 .allow_daemon_threads = 0,
1761 .check_multi_interp_extensions = 1,
1762 .gil = PyInterpreterConfig_OWN_GIL,
1763 };
1764 PyThreadState *tstate = NULL;
1765 PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
1766 if (PyStatus_Exception(status)) {
1767 Py_ExitStatusException(status);
1768 }
1769
1770 Note that the config is used only briefly and does not get modified.
1771 During initialization the config's values are converted into various
1772 :c:type:`PyInterpreterState` values. A read-only copy of the config
1773 may be stored internally on the :c:type:`PyInterpreterState`.
1774
1775 .. index::
1776 single: Py_FinalizeEx (C function)
1777 single: Py_Initialize (C function)
1778
1779 Extension modules are shared between (sub-)interpreters as follows:
1780
1781 * For modules using multi-phase initialization,
1782 e.g. :c:func:`PyModule_FromDefAndSpec`, a separate module object is
1783 created and initialized for each interpreter.
1784 Only C-level static and global variables are shared between these
1785 module objects.
1786
1787 * For modules using single-phase initialization,
1788 e.g. :c:func:`PyModule_Create`, the first time a particular extension
1789 is imported, it is initialized normally, and a (shallow) copy of its
1790 module's dictionary is squirreled away.
1791 When the same extension is imported by another (sub-)interpreter, a new
1792 module is initialized and filled with the contents of this copy; the
1793 extension's ``init`` function is not called.
1794 Objects in the module's dictionary thus end up shared across
1795 (sub-)interpreters, which might cause unwanted behavior (see
1796 `Bugs and caveats`_ below).
1797
1798 Note that this is different from what happens when an extension is
1799 imported after the interpreter has been completely re-initialized by
1800 calling :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that
1801 case, the extension's ``initmodule`` function *is* called again.
1802 As with multi-phase initialization, this means that only C-level static
1803 and global variables are shared between these modules.
1804
1805 .. index:: single: close (in module os)
1806
1807
1808 .. c:function:: PyThreadState* Py_NewInterpreter(void)
1809
1810 .. index::
1811 pair: module; builtins
1812 pair: module; __main__
1813 pair: module; sys
1814 single: stdout (in module sys)
1815 single: stderr (in module sys)
1816 single: stdin (in module sys)
1817
1818 Create a new sub-interpreter. This is essentially just a wrapper
1819 around :c:func:`Py_NewInterpreterFromConfig` with a config that
1820 preserves the existing behavior. The result is an unisolated
1821 sub-interpreter that shares the main interpreter's GIL, allows
1822 fork/exec, allows daemon threads, and allows single-phase init
1823 modules.
1824
1825
1826 .. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
1827
1828 .. index:: single: Py_FinalizeEx (C function)
1829
1830 Destroy the (sub-)interpreter represented by the given thread state.
1831 The given thread state must be the current thread state. See the
1832 discussion of thread states below. When the call returns,
1833 the current thread state is ``NULL``. All thread states associated
1834 with this interpreter are destroyed. The global interpreter lock
1835 used by the target interpreter must be held before calling this
1836 function. No GIL is held when it returns.
1837
1838 :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
1839 haven't been explicitly destroyed at that point.
1840
1841
1842 .. _per-interpreter-gil:
1843
1844 A Per-Interpreter GIL
1845 ---------------------
1846
1847 Using :c:func:`Py_NewInterpreterFromConfig` you can create
1848 a sub-interpreter that is completely isolated from other interpreters,
1849 including having its own GIL. The most important benefit of this
1850 isolation is that such an interpreter can execute Python code without
1851 being blocked by other interpreters or blocking any others. Thus a
1852 single Python process can truly take advantage of multiple CPU cores
1853 when running Python code. The isolation also encourages a different
1854 approach to concurrency than that of just using threads.
1855 (See :pep:`554` and :pep:`684`.)
1856
1857 Using an isolated interpreter requires vigilance in preserving that
1858 isolation. That especially means not sharing any objects or mutable
1859 state without guarantees about thread-safety. Even objects that are
1860 otherwise immutable (e.g. ``None``, ``(1, 5)``) can't normally be shared
1861 because of the refcount. One simple but less-efficient approach around
1862 this is to use a global lock around all use of some state (or object).
1863 Alternately, effectively immutable objects (like integers or strings)
1864 can be made safe in spite of their refcounts by making them :term:`immortal`.
1865 In fact, this has been done for the builtin singletons, small integers,
1866 and a number of other builtin objects.
1867
1868 If you preserve isolation then you will have access to proper multi-core
1869 computing without the complications that come with free-threading.
1870 Failure to preserve isolation will expose you to the full consequences
1871 of free-threading, including races and hard-to-debug crashes.
1872
1873 Aside from that, one of the main challenges of using multiple isolated
1874 interpreters is how to communicate between them safely (not break
1875 isolation) and efficiently. The runtime and stdlib do not provide
1876 any standard approach to this yet. A future stdlib module would help
1877 mitigate the effort of preserving isolation and expose effective tools
1878 for communicating (and sharing) data between interpreters.
1879
1880 .. versionadded:: 3.12
1881
1882
1883 Bugs and caveats
1884 ----------------
1885
1886 Because sub-interpreters (and the main interpreter) are part of the same
1887 process, the insulation between them isn't perfect --- for example, using
1888 low-level file operations like :func:`os.close` they can
1889 (accidentally or maliciously) affect each other's open files. Because of the
1890 way extensions are shared between (sub-)interpreters, some extensions may not
1891 work properly; this is especially likely when using single-phase initialization
1892 or (static) global variables.
1893 It is possible to insert objects created in one sub-interpreter into
1894 a namespace of another (sub-)interpreter; this should be avoided if possible.
1895
1896 Special care should be taken to avoid sharing user-defined functions,
1897 methods, instances or classes between sub-interpreters, since import
1898 operations executed by such objects may affect the wrong (sub-)interpreter's
1899 dictionary of loaded modules. It is equally important to avoid sharing
1900 objects from which the above are reachable.
1901
1902 Also note that combining this functionality with ``PyGILState_*`` APIs
1903 is delicate, because these APIs assume a bijection between Python thread states
1904 and OS-level threads, an assumption broken by the presence of sub-interpreters.
1905 It is highly recommended that you don't switch sub-interpreters between a pair
1906 of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
1907 Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
1908 of Python code from non-Python created threads will probably be broken when using
1909 sub-interpreters.
1910
1911
1912 Asynchronous Notifications
1913 ==========================
1914
1915 A mechanism is provided to make asynchronous notifications to the main
1916 interpreter thread. These notifications take the form of a function
1917 pointer and a void pointer argument.
1918
1919
1920 .. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
1921
1922 Schedule a function to be called from the main interpreter thread. On
1923 success, ``0`` is returned and *func* is queued for being called in the
1924 main thread. On failure, ``-1`` is returned without setting any exception.
1925
1926 When successfully queued, *func* will be *eventually* called from the
1927 main interpreter thread with the argument *arg*. It will be called
1928 asynchronously with respect to normally running Python code, but with
1929 both these conditions met:
1930
1931 * on a :term:`bytecode` boundary;
1932 * with the main thread holding the :term:`global interpreter lock`
1933 (*func* can therefore use the full C API).
1934
1935 *func* must return ``0`` on success, or ``-1`` on failure with an exception
1936 set. *func* won't be interrupted to perform another asynchronous
1937 notification recursively, but it can still be interrupted to switch
1938 threads if the global interpreter lock is released.
1939
1940 This function doesn't need a current thread state to run, and it doesn't
1941 need the global interpreter lock.
1942
1943 To call this function in a subinterpreter, the caller must hold the GIL.
1944 Otherwise, the function *func* can be scheduled to be called from the wrong
1945 interpreter.
1946
1947 .. warning::
1948 This is a low-level function, only useful for very special cases.
1949 There is no guarantee that *func* will be called as quick as
1950 possible. If the main thread is busy executing a system call,
1951 *func* won't be called before the system call returns. This
1952 function is generally **not** suitable for calling Python code from
1953 arbitrary C threads. Instead, use the :ref:`PyGILState API<gilstate>`.
1954
1955 .. versionadded:: 3.1
1956
1957 .. versionchanged:: 3.9
1958 If this function is called in a subinterpreter, the function *func* is
1959 now scheduled to be called from the subinterpreter, rather than being
1960 called from the main interpreter. Each subinterpreter now has its own
1961 list of scheduled calls.
1962
1963 .. versionchanged:: 3.12
1964 This function now always schedules *func* to be run in the main
1965 interpreter.
1966
1967
1968 .. c:function:: int Py_MakePendingCalls(void)
1969
1970 Execute all pending calls. This is usually executed automatically by the
1971 interpreter.
1972
1973 This function returns ``0`` on success, and returns ``-1`` with an exception
1974 set on failure.
1975
1976 If this is not called in the main thread of the main
1977 interpreter, this function does nothing and returns ``0``.
1978 The caller must hold the :term:`GIL`.
1979
1980 .. versionadded:: 3.1
1981
1982 .. versionchanged:: 3.12
1983 This function only runs pending calls in the main interpreter.
1984
1985
1986 .. _profiling:
1987
1988 Profiling and Tracing
1989 =====================
1990
1991 .. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
1992
1993
1994 The Python interpreter provides some low-level support for attaching profiling
1995 and execution tracing facilities. These are used for profiling, debugging, and
1996 coverage analysis tools.
1997
1998 This C interface allows the profiling or tracing code to avoid the overhead of
1999 calling through Python-level callable objects, making a direct C function call
2000 instead. The essential attributes of the facility have not changed; the
2001 interface allows trace functions to be installed per-thread, and the basic
2002 events reported to the trace function are the same as had been reported to the
2003 Python-level trace functions in previous versions.
2004
2005
2006 .. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
2007
2008 The type of the trace function registered using :c:func:`PyEval_SetProfile` and
2009 :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
2010 registration function as *obj*, *frame* is the frame object to which the event
2011 pertains, *what* is one of the constants :c:data:`PyTrace_CALL`,
2012 :c:data:`PyTrace_EXCEPTION`, :c:data:`PyTrace_LINE`, :c:data:`PyTrace_RETURN`,
2013 :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION`, :c:data:`PyTrace_C_RETURN`,
2014 or :c:data:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
2015
2016 +-------------------------------+----------------------------------------+
2017 | Value of *what* | Meaning of *arg* |
2018 +===============================+========================================+
2019 | :c:data:`PyTrace_CALL` | Always :c:data:`Py_None`. |
2020 +-------------------------------+----------------------------------------+
2021 | :c:data:`PyTrace_EXCEPTION` | Exception information as returned by |
2022 | | :func:`sys.exc_info`. |
2023 +-------------------------------+----------------------------------------+
2024 | :c:data:`PyTrace_LINE` | Always :c:data:`Py_None`. |
2025 +-------------------------------+----------------------------------------+
2026 | :c:data:`PyTrace_RETURN` | Value being returned to the caller, |
2027 | | or ``NULL`` if caused by an exception. |
2028 +-------------------------------+----------------------------------------+
2029 | :c:data:`PyTrace_C_CALL` | Function object being called. |
2030 +-------------------------------+----------------------------------------+
2031 | :c:data:`PyTrace_C_EXCEPTION` | Function object being called. |
2032 +-------------------------------+----------------------------------------+
2033 | :c:data:`PyTrace_C_RETURN` | Function object being called. |
2034 +-------------------------------+----------------------------------------+
2035 | :c:data:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
2036 +-------------------------------+----------------------------------------+
2037
2038 .. c:var:: int PyTrace_CALL
2039
2040 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
2041 call to a function or method is being reported, or a new entry into a generator.
2042 Note that the creation of the iterator for a generator function is not reported
2043 as there is no control transfer to the Python bytecode in the corresponding
2044 frame.
2045
2046
2047 .. c:var:: int PyTrace_EXCEPTION
2048
2049 The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
2050 exception has been raised. The callback function is called with this value for
2051 *what* when after any bytecode is processed after which the exception becomes
2052 set within the frame being executed. The effect of this is that as exception
2053 propagation causes the Python stack to unwind, the callback is called upon
2054 return to each frame as the exception propagates. Only trace functions receives
2055 these events; they are not needed by the profiler.
2056
2057
2058 .. c:var:: int PyTrace_LINE
2059
2060 The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
2061 (but not a profiling function) when a line-number event is being reported.
2062 It may be disabled for a frame by setting :attr:`~frame.f_trace_lines` to
2063 *0* on that frame.
2064
2065
2066 .. c:var:: int PyTrace_RETURN
2067
2068 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
2069 call is about to return.
2070
2071
2072 .. c:var:: int PyTrace_C_CALL
2073
2074 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
2075 function is about to be called.
2076
2077
2078 .. c:var:: int PyTrace_C_EXCEPTION
2079
2080 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
2081 function has raised an exception.
2082
2083
2084 .. c:var:: int PyTrace_C_RETURN
2085
2086 The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
2087 function has returned.
2088
2089
2090 .. c:var:: int PyTrace_OPCODE
2091
2092 The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
2093 profiling functions) when a new opcode is about to be executed. This event is
2094 not emitted by default: it must be explicitly requested by setting
2095 :attr:`~frame.f_trace_opcodes` to *1* on the frame.
2096
2097
2098 .. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
2099
2100 Set the profiler function to *func*. The *obj* parameter is passed to the
2101 function as its first parameter, and may be any Python object, or ``NULL``. If
2102 the profile function needs to maintain state, using a different value for *obj*
2103 for each thread provides a convenient and thread-safe place to store it. The
2104 profile function is called for all monitored events except :c:data:`PyTrace_LINE`
2105 :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`.
2106
2107 See also the :func:`sys.setprofile` function.
2108
2109 The caller must hold the :term:`GIL`.
2110
2111 .. c:function:: void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
2112
2113 Like :c:func:`PyEval_SetProfile` but sets the profile function in all running threads
2114 belonging to the current interpreter instead of the setting it only on the current thread.
2115
2116 The caller must hold the :term:`GIL`.
2117
2118 As :c:func:`PyEval_SetProfile`, this function ignores any exceptions raised while
2119 setting the profile functions in all threads.
2120
2121 .. versionadded:: 3.12
2122
2123
2124 .. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
2125
2126 Set the tracing function to *func*. This is similar to
2127 :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
2128 events and per-opcode events, but does not receive any event related to C function
2129 objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
2130 will not receive :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION` or
2131 :c:data:`PyTrace_C_RETURN` as a value for the *what* parameter.
2132
2133 See also the :func:`sys.settrace` function.
2134
2135 The caller must hold the :term:`GIL`.
2136
2137 .. c:function:: void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
2138
2139 Like :c:func:`PyEval_SetTrace` but sets the tracing function in all running threads
2140 belonging to the current interpreter instead of the setting it only on the current thread.
2141
2142 The caller must hold the :term:`GIL`.
2143
2144 As :c:func:`PyEval_SetTrace`, this function ignores any exceptions raised while
2145 setting the trace functions in all threads.
2146
2147 .. versionadded:: 3.12
2148
2149 Reference tracing
2150 =================
2151
2152 .. versionadded:: 3.13
2153
2154 .. c:type:: int (*PyRefTracer)(PyObject *, int event, void* data)
2155
2156 The type of the trace function registered using :c:func:`PyRefTracer_SetTracer`.
2157 The first parameter is a Python object that has been just created (when **event**
2158 is set to :c:data:`PyRefTracer_CREATE`) or about to be destroyed (when **event**
2159 is set to :c:data:`PyRefTracer_DESTROY`). The **data** argument is the opaque pointer
2160 that was provided when :c:func:`PyRefTracer_SetTracer` was called.
2161
2162 .. versionadded:: 3.13
2163
2164 .. c:var:: int PyRefTracer_CREATE
2165
2166 The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
2167 object has been created.
2168
2169 .. c:var:: int PyRefTracer_DESTROY
2170
2171 The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
2172 object has been destroyed.
2173
2174 .. c:function:: int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)
2175
2176 Register a reference tracer function. The function will be called when a new
2177 Python has been created or when an object is going to be destroyed. If
2178 **data** is provided it must be an opaque pointer that will be provided when
2179 the tracer function is called. Return ``0`` on success. Set an exception and
2180 return ``-1`` on error.
2181
2182 Not that tracer functions **must not** create Python objects inside or
2183 otherwise the call will be re-entrant. The tracer also **must not** clear
2184 any existing exception or set an exception. The GIL will be held every time
2185 the tracer function is called.
2186
2187 The GIL must be held when calling this function.
2188
2189 .. versionadded:: 3.13
2190
2191 .. c:function:: PyRefTracer PyRefTracer_GetTracer(void** data)
2192
2193 Get the registered reference tracer function and the value of the opaque data
2194 pointer that was registered when :c:func:`PyRefTracer_SetTracer` was called.
2195 If no tracer was registered this function will return NULL and will set the
2196 **data** pointer to NULL.
2197
2198 The GIL must be held when calling this function.
2199
2200 .. versionadded:: 3.13
2201
2202 .. _advanced-debugging:
2203
2204 Advanced Debugger Support
2205 =========================
2206
2207 .. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
2208
2209
2210 These functions are only intended to be used by advanced debugging tools.
2211
2212
2213 .. c:function:: PyInterpreterState* PyInterpreterState_Head()
2214
2215 Return the interpreter state object at the head of the list of all such objects.
2216
2217
2218 .. c:function:: PyInterpreterState* PyInterpreterState_Main()
2219
2220 Return the main interpreter state object.
2221
2222
2223 .. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
2224
2225 Return the next interpreter state object after *interp* from the list of all
2226 such objects.
2227
2228
2229 .. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
2230
2231 Return the pointer to the first :c:type:`PyThreadState` object in the list of
2232 threads associated with the interpreter *interp*.
2233
2234
2235 .. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
2236
2237 Return the next thread state object after *tstate* from the list of all such
2238 objects belonging to the same :c:type:`PyInterpreterState` object.
2239
2240
2241 .. _thread-local-storage:
2242
2243 Thread Local Storage Support
2244 ============================
2245
2246 .. sectionauthor:: Masayuki Yamamoto <[email protected]>
2247
2248 The Python interpreter provides low-level support for thread-local storage
2249 (TLS) which wraps the underlying native TLS implementation to support the
2250 Python-level thread local storage API (:class:`threading.local`). The
2251 CPython C level APIs are similar to those offered by pthreads and Windows:
2252 use a thread key and functions to associate a :c:expr:`void*` value per
2253 thread.
2254
2255 The GIL does *not* need to be held when calling these functions; they supply
2256 their own locking.
2257
2258 Note that :file:`Python.h` does not include the declaration of the TLS APIs,
2259 you need to include :file:`pythread.h` to use thread-local storage.
2260
2261 .. note::
2262 None of these API functions handle memory management on behalf of the
2263 :c:expr:`void*` values. You need to allocate and deallocate them yourself.
2264 If the :c:expr:`void*` values happen to be :c:expr:`PyObject*`, these
2265 functions don't do refcount operations on them either.
2266
2267 .. _thread-specific-storage-api:
2268
2269 Thread Specific Storage (TSS) API
2270 ---------------------------------
2271
2272 TSS API is introduced to supersede the use of the existing TLS API within the
2273 CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
2274 :c:expr:`int` to represent thread keys.
2275
2276 .. versionadded:: 3.7
2277
2278 .. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
2279
2280
2281 .. c:type:: Py_tss_t
2282
2283 This data structure represents the state of a thread key, the definition of
2284 which may depend on the underlying TLS implementation, and it has an
2285 internal field representing the key's initialization state. There are no
2286 public members in this structure.
2287
2288 When :ref:`Py_LIMITED_API <stable>` is not defined, static allocation of
2289 this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
2290
2291
2292 .. c:macro:: Py_tss_NEEDS_INIT
2293
2294 This macro expands to the initializer for :c:type:`Py_tss_t` variables.
2295 Note that this macro won't be defined with :ref:`Py_LIMITED_API <stable>`.
2296
2297
2298 Dynamic Allocation
2299 ~~~~~~~~~~~~~~~~~~
2300
2301 Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
2302 built with :ref:`Py_LIMITED_API <stable>`, where static allocation of this type
2303 is not possible due to its implementation being opaque at build time.
2304
2305
2306 .. c:function:: Py_tss_t* PyThread_tss_alloc()
2307
2308 Return a value which is the same state as a value initialized with
2309 :c:macro:`Py_tss_NEEDS_INIT`, or ``NULL`` in the case of dynamic allocation
2310 failure.
2311
2312
2313 .. c:function:: void PyThread_tss_free(Py_tss_t *key)
2314
2315 Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
2316 first calling :c:func:`PyThread_tss_delete` to ensure any associated
2317 thread locals have been unassigned. This is a no-op if the *key*
2318 argument is ``NULL``.
2319
2320 .. note::
2321 A freed key becomes a dangling pointer. You should reset the key to
2322 ``NULL``.
2323
2324
2325 Methods
2326 ~~~~~~~
2327
2328 The parameter *key* of these functions must not be ``NULL``. Moreover, the
2329 behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
2330 undefined if the given :c:type:`Py_tss_t` has not been initialized by
2331 :c:func:`PyThread_tss_create`.
2332
2333
2334 .. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
2335
2336 Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
2337 by :c:func:`PyThread_tss_create`.
2338
2339
2340 .. c:function:: int PyThread_tss_create(Py_tss_t *key)
2341
2342 Return a zero value on successful initialization of a TSS key. The behavior
2343 is undefined if the value pointed to by the *key* argument is not
2344 initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
2345 repeatedly on the same key -- calling it on an already initialized key is a
2346 no-op and immediately returns success.
2347
2348
2349 .. c:function:: void PyThread_tss_delete(Py_tss_t *key)
2350
2351 Destroy a TSS key to forget the values associated with the key across all
2352 threads, and change the key's initialization state to uninitialized. A
2353 destroyed key is able to be initialized again by
2354 :c:func:`PyThread_tss_create`. This function can be called repeatedly on
2355 the same key -- calling it on an already destroyed key is a no-op.
2356
2357
2358 .. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
2359
2360 Return a zero value to indicate successfully associating a :c:expr:`void*`
2361 value with a TSS key in the current thread. Each thread has a distinct
2362 mapping of the key to a :c:expr:`void*` value.
2363
2364
2365 .. c:function:: void* PyThread_tss_get(Py_tss_t *key)
2366
2367 Return the :c:expr:`void*` value associated with a TSS key in the current
2368 thread. This returns ``NULL`` if no value is associated with the key in the
2369 current thread.
2370
2371
2372 .. _thread-local-storage-api:
2373
2374 Thread Local Storage (TLS) API
2375 ------------------------------
2376
2377 .. deprecated:: 3.7
2378 This API is superseded by
2379 :ref:`Thread Specific Storage (TSS) API <thread-specific-storage-api>`.
2380
2381 .. note::
2382 This version of the API does not support platforms where the native TLS key
2383 is defined in a way that cannot be safely cast to ``int``. On such platforms,
2384 :c:func:`PyThread_create_key` will return immediately with a failure status,
2385 and the other TLS functions will all be no-ops on such platforms.
2386
2387 Due to the compatibility problem noted above, this version of the API should not
2388 be used in new code.
2389
2390 .. c:function:: int PyThread_create_key()
2391 .. c:function:: void PyThread_delete_key(int key)
2392 .. c:function:: int PyThread_set_key_value(int key, void *value)
2393 .. c:function:: void* PyThread_get_key_value(int key)
2394 .. c:function:: void PyThread_delete_key_value(int key)
2395 .. c:function:: void PyThread_ReInitTLS()
2396
2397 Synchronization Primitives
2398 ==========================
2399
2400 The C-API provides a basic mutual exclusion lock.
2401
2402 .. c:type:: PyMutex
2403
2404 A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to
2405 zero to represent the unlocked state. For example::
2406
2407 PyMutex mutex = {0};
2408
2409 Instances of :c:type:`!PyMutex` should not be copied or moved. Both the
2410 contents and address of a :c:type:`!PyMutex` are meaningful, and it must
2411 remain at a fixed, writable location in memory.
2412
2413 .. note::
2414
2415 A :c:type:`!PyMutex` currently occupies one byte, but the size should be
2416 considered unstable. The size may change in future Python releases
2417 without a deprecation period.
2418
2419 .. versionadded:: 3.13
2420
2421 .. c:function:: void PyMutex_Lock(PyMutex *m)
2422
2423 Lock mutex *m*. If another thread has already locked it, the calling
2424 thread will block until the mutex is unlocked. While blocked, the thread
2425 will temporarily release the :term:`GIL` if it is held.
2426
2427 .. versionadded:: 3.13
2428
2429 .. c:function:: void PyMutex_Unlock(PyMutex *m)
2430
2431 Unlock mutex *m*. The mutex must be locked --- otherwise, the function will
2432 issue a fatal error.
2433
2434 .. versionadded:: 3.13
2435
2436 .. _python-critical-section-api:
2437
2438 Python Critical Section API
2439 ---------------------------
2440
2441 The critical section API provides a deadlock avoidance layer on top of
2442 per-object locks for :term:`free-threaded <free threading>` CPython. They are
2443 intended to replace reliance on the :term:`global interpreter lock`, and are
2444 no-ops in versions of Python with the global interpreter lock.
2445
2446 Critical sections are intended to be used for custom types implemented
2447 in C-API extensions. They should generally not be used with built-in types like
2448 :class:`list` and :class:`dict` because their public C-APIs
2449 already use critical sections internally, with the notable
2450 exception of :c:func:`PyDict_Next`, which requires critical section
2451 to be acquired externally.
2452
2453 Critical sections avoid deadlocks by implicitly suspending active critical
2454 sections, hence, they do not provide exclusive access such as provided by
2455 traditional locks like :c:type:`PyMutex`. When a critical section is started,
2456 the per-object lock for the object is acquired. If the code executed inside the
2457 critical section calls C-API functions then it can suspend the critical section thereby
2458 releasing the per-object lock, so other threads can acquire the per-object lock
2459 for the same object.
2460
2461 The functions and structs used by the macros are exposed for cases
2462 where C macros are not available. They should only be used as in the
2463 given macro expansions. Note that the sizes and contents of the structures may
2464 change in future Python versions.
2465
2466 .. note::
2467
2468 Operations that need to lock two objects at once must use
2469 :c:macro:`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical
2470 sections to lock more than one object at once, because the inner critical
2471 section may suspend the outer critical sections. This API does not provide
2472 a way to lock more than two objects at once.
2473
2474 Example usage::
2475
2476 static PyObject *
2477 set_field(MyObject *self, PyObject *value)
2478 {
2479 Py_BEGIN_CRITICAL_SECTION(self);
2480 Py_SETREF(self->field, Py_XNewRef(value));
2481 Py_END_CRITICAL_SECTION();
2482 Py_RETURN_NONE;
2483 }
2484
2485 In the above example, :c:macro:`Py_SETREF` calls :c:macro:`Py_DECREF`, which
2486 can call arbitrary code through an object's deallocation function. The critical
2487 section API avoids potential deadlocks due to reentrancy and lock ordering
2488 by allowing the runtime to temporarily suspend the critical section if the
2489 code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`.
2490
2491 .. c:macro:: Py_BEGIN_CRITICAL_SECTION(op)
2492
2493 Acquires the per-object lock for the object *op* and begins a
2494 critical section.
2495
2496 In the free-threaded build, this macro expands to::
2497
2498 {
2499 PyCriticalSection _py_cs;
2500 PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
2501
2502 In the default build, this macro expands to ``{``.
2503
2504 .. versionadded:: 3.13
2505
2506 .. c:macro:: Py_END_CRITICAL_SECTION()
2507
2508 Ends the critical section and releases the per-object lock.
2509
2510 In the free-threaded build, this macro expands to::
2511
2512 PyCriticalSection_End(&_py_cs);
2513 }
2514
2515 In the default build, this macro expands to ``}``.
2516
2517 .. versionadded:: 3.13
2518
2519 .. c:macro:: Py_BEGIN_CRITICAL_SECTION2(a, b)
2520
2521 Acquires the per-objects locks for the objects *a* and *b* and begins a
2522 critical section. The locks are acquired in a consistent order (lowest
2523 address first) to avoid lock ordering deadlocks.
2524
2525 In the free-threaded build, this macro expands to::
2526
2527 {
2528 PyCriticalSection2 _py_cs2;
2529 PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
2530
2531 In the default build, this macro expands to ``{``.
2532
2533 .. versionadded:: 3.13
2534
2535 .. c:macro:: Py_END_CRITICAL_SECTION2()
2536
2537 Ends the critical section and releases the per-object locks.
2538
2539 In the free-threaded build, this macro expands to::
2540
2541 PyCriticalSection2_End(&_py_cs2);
2542 }
2543
2544 In the default build, this macro expands to ``}``.
2545
2546 .. versionadded:: 3.13
2547
2548
2549 Legacy Locking APIs
2550 -------------------
2551
2552 These APIs are obsolete since Python 3.13 with the introduction of
2553 :c:type:`PyMutex`.
2554
2555 .. versionchanged:: 3.15
2556 These APIs are now a simple wrapper around ``PyMutex``.
2557
2558
2559 .. c:type:: PyThread_type_lock
2560
2561 A pointer to a mutual exclusion lock.
2562
2563
2564 .. c:type:: PyLockStatus
2565
2566 The result of acquiring a lock with a timeout.
2567
2568 .. c:namespace:: NULL
2569
2570 .. c:enumerator:: PY_LOCK_FAILURE
2571
2572 Failed to acquire the lock.
2573
2574 .. c:enumerator:: PY_LOCK_ACQUIRED
2575
2576 The lock was successfully acquired.
2577
2578 .. c:enumerator:: PY_LOCK_INTR
2579
2580 The lock was interrupted by a signal.
2581
2582
2583 .. c:function:: PyThread_type_lock PyThread_allocate_lock(void)
2584
2585 Allocate a new lock.
2586
2587 On success, this function returns a lock; on failure, this
2588 function returns ``0`` without an exception set.
2589
2590 The caller does not need to hold the :term:`GIL`.
2591
2592 .. versionchanged:: 3.15
2593 This function now always uses :c:type:`PyMutex`. In prior versions, this
2594 would use a lock provided by the operating system.
2595
2596
2597 .. c:function:: void PyThread_free_lock(PyThread_type_lock lock)
2598
2599 Destroy *lock*. The lock should not be held by any thread when calling
2600 this.
2601
2602 The caller does not need to hold the :term:`GIL`.
2603
2604
2605 .. c:function:: PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
2606
2607 Acquire *lock* with a timeout.
2608
2609 This will wait for *microseconds* microseconds to acquire the lock. If the
2610 timeout expires, this function returns :c:enumerator:`PY_LOCK_FAILURE`.
2611 If *microseconds* is ``-1``, this will wait indefinitely until the lock has
2612 been released.
2613
2614 If *intr_flag* is ``1``, acquiring the lock may be interrupted by a signal,
2615 in which case this function returns :c:enumerator:`PY_LOCK_INTR`. Upon
2616 interruption, it's generally expected that the caller makes a call to
2617 :c:func:`Py_MakePendingCalls` to propagate an exception to Python code.
2618
2619 If the lock is successfully acquired, this function returns
2620 :c:enumerator:`PY_LOCK_ACQUIRED`.
2621
2622 The caller does not need to hold the :term:`GIL`.
2623
2624
2625 .. c:function:: int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
2626
2627 Acquire *lock*.
2628
2629 If *waitflag* is ``1`` and another thread currently holds the lock, this
2630 function will wait until the lock can be acquired and will always return
2631 ``1``.
2632
2633 If *waitflag* is ``0`` and another thread holds the lock, this function will
2634 not wait and instead return ``0``. If the lock is not held by any other
2635 thread, then this function will acquire it and return ``1``.
2636
2637 Unlike :c:func:`PyThread_acquire_lock_timed`, acquiring the lock cannot be
2638 interrupted by a signal.
2639
2640 The caller does not need to hold the :term:`GIL`.
2641
2642
2643 .. c:function:: int PyThread_release_lock(PyThread_type_lock lock)
2644
2645 Release *lock*. If *lock* is not held, then this function issues a
2646 fatal error.
2647
2648 The caller does not need to hold the :term:`GIL`.
2649
2650
2651 Operating System Thread APIs
2652 ============================
2653
2654 .. c:macro:: PYTHREAD_INVALID_THREAD_ID
2655
2656 Sentinel value for an invalid thread ID.
2657
2658 This is currently equivalent to ``(unsigned long)-1``.
2659
2660
2661 .. c:function:: unsigned long PyThread_start_new_thread(void (*func)(void *), void *arg)
2662
2663 Start function *func* in a new thread with argument *arg*.
2664 The resulting thread is not intended to be joined.
2665
2666 *func* must not be ``NULL``, but *arg* may be ``NULL``.
2667
2668 On success, this function returns the identifier of the new thread; on failure,
2669 this returns :c:macro:`PYTHREAD_INVALID_THREAD_ID`.
2670
2671 The caller does not need to hold the :term:`GIL`.
2672
2673
2674 .. c:function:: unsigned long PyThread_get_thread_ident(void)
2675
2676 Return the identifier of the current thread, which will never be zero.
2677
2678 This function cannot fail, and the caller does not need to hold the
2679 :term:`GIL`.
2680
2681 .. seealso::
2682 :py:func:`threading.get_ident`
2683
2684
2685 .. c:function:: PyObject *PyThread_GetInfo(void)
2686
2687 Get general information about the current thread in the form of a
2688 :ref:`struct sequence <struct-sequence-objects>` object. This information is
2689 accessible as :py:attr:`sys.thread_info` in Python.
2690
2691 On success, this returns a new :term:`strong reference` to the thread
2692 information; on failure, this returns ``NULL`` with an exception set.
2693
2694 The caller must hold the :term:`GIL`.
2695
2696
2697 .. c:macro:: PY_HAVE_THREAD_NATIVE_ID
2698
2699 This macro is defined when the system supports native thread IDs.
2700
2701
2702 .. c:function:: unsigned long PyThread_get_thread_native_id(void)
2703
2704 Get the native identifier of the current thread as it was assigned by the operating
2705 system's kernel, which will never be less than zero.
2706
2707 This function is only available when :c:macro:`PY_HAVE_THREAD_NATIVE_ID` is
2708 defined.
2709
2710 This function cannot fail, and the caller does not need to hold the
2711 :term:`GIL`.
2712
2713 .. seealso::
2714 :py:func:`threading.get_native_id`
2715
2716
2717 .. c:function:: void PyThread_exit_thread(void)
2718
2719 Terminate the current thread. This function is generally considered unsafe
2720 and should be avoided. It is kept solely for backwards compatibility.
2721
2722 This function is only safe to call if all functions in the full call
2723 stack are written to safely allow it.
2724
2725 .. warning::
2726
2727 If the current system uses POSIX threads (also known as "pthreads"),
2728 this calls :manpage:`pthread_exit(3)`, which attempts to unwind the stack
2729 and call C++ destructors on some libc implementations. However, if a
2730 ``noexcept`` function is reached, it may terminate the process.
2731 Other systems, such as macOS, do unwinding.
2732
2733 On Windows, this function calls ``_endthreadex()``, which kills the thread
2734 without calling C++ destructors.
2735
2736 In any case, there is a risk of corruption on the thread's stack.
2737
2738
2739 .. c:function:: void PyThread_init_thread(void)
2740
2741 Initialize ``PyThread*`` APIs. Python executes this function automatically,
2742 so there's little need to call it from an extension module.
2743
2744
2745 .. c:function:: int PyThread_set_stacksize(size_t size)
2746
2747 Set the stack size of the current thread to *size* bytes.
2748
2749 This function returns ``0`` on success, ``-1`` if *size* is invalid, or
2750 ``-2`` if the system does not support changing the stack size. This function
2751 does not set exceptions.
2752
2753 The caller does not need to hold the :term:`GIL`.
2754
2755
2756 .. c:function:: size_t PyThread_get_stacksize(void)
2757
2758 Return the stack size of the current thread in bytes, or ``0`` if the system's
2759 default stack size is in use.
2760
2761 The caller does not need to hold the :term:`GIL`.