@@ -447,7 +447,11 @@ Initializing and finalizing the interpreter
447
447
freed. Some memory allocated by extension modules may not be freed. Some
448
448
extensions may not work properly if their initialization routine is called more
449
449
than once; this can happen if an application calls :c:func:`Py_Initialize` and
450
- :c:func: `Py_FinalizeEx ` more than once.
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.
451
455
452
456
.. audit-event :: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx
453
457
@@ -1074,6 +1078,37 @@ thread, where the CPython global runtime was originally initialized.
1074
1078
The only exception is if :c:func:`exec` will be called immediately
1075
1079
after.
1076
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
+
1077
1112
1078
1113
High-level API
1079
1114
--------------
@@ -1093,6 +1128,12 @@ code, or when embedding the Python interpreter:
1093
1128
interpreter lock is also shared by all threads, regardless of to which
1094
1129
interpreter they belong.
1095
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
+
1096
1137
1097
1138
.. c:type:: PyThreadState
1098
1139
@@ -1147,11 +1188,14 @@ code, or when embedding the Python interpreter:
1147
1188
ensues.
1148
1189
1149
1190
.. note::
1150
- Calling this function from a thread when the runtime is finalizing
1151
- will terminate the thread, even if the thread was not created by Python.
1152
- You can use :c:func:`Py_IsFinalizing` or :func:`sys.is_finalizing` to
1153
- check if the interpreter is in process of being finalized before calling
1154
- this function to avoid unwanted termination.
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:: next
1197
+ Hangs the current thread, rather than terminating it, if called while the
1198
+ interpreter is finalizing.
1155
1199
1156
1200
.. c:function:: PyThreadState* PyThreadState_Get()
1157
1201
@@ -1207,11 +1251,14 @@ with sub-interpreters:
1207
1251
to call arbitrary Python code. Failure is a fatal error.
1208
1252
1209
1253
.. note::
1210
- Calling this function from a thread when the runtime is finalizing
1211
- will terminate the thread, even if the thread was not created by Python.
1212
- You can use :c:func:`Py_IsFinalizing` or :func:`sys.is_finalizing` to
1213
- check if the interpreter is in process of being finalized before calling
1214
- this function to avoid unwanted termination.
1254
+ Calling this function from a thread when the runtime is finalizing will
1255
+ hang the thread until the program exits, even if the thread was not
1256
+ created by Python. Refer to
1257
+ :ref:`cautions-regarding-runtime-finalization` for more details.
1258
+
1259
+ .. versionchanged:: next
1260
+ Hangs the current thread, rather than terminating it, if called while the
1261
+ interpreter is finalizing.
1215
1262
1216
1263
.. c:function:: void PyGILState_Release(PyGILState_STATE)
1217
1264
@@ -1503,17 +1550,20 @@ All of the following functions must be called after :c:func:`Py_Initialize`.
1503
1550
If this thread already has the lock, deadlock ensues.
1504
1551
1505
1552
.. note::
1506
- Calling this function from a thread when the runtime is finalizing
1507
- will terminate the thread, even if the thread was not created by Python.
1508
- You can use :c:func:`Py_IsFinalizing` or :func:`sys.is_finalizing` to
1509
- check if the interpreter is in process of being finalized before calling
1510
- this function to avoid unwanted termination.
1553
+ Calling this function from a thread when the runtime is finalizing will
1554
+ hang the thread until the program exits, even if the thread was not
1555
+ created by Python. Refer to
1556
+ :ref:`cautions-regarding-runtime-finalization` for more details.
1511
1557
1512
1558
.. versionchanged:: 3.8
1513
1559
Updated to be consistent with :c:func:`PyEval_RestoreThread`,
1514
1560
:c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
1515
1561
and terminate the current thread if called while the interpreter is finalizing.
1516
1562
1563
+ .. versionchanged:: next
1564
+ Hangs the current thread, rather than terminating it, if called while the
1565
+ interpreter is finalizing.
1566
+
1517
1567
:c:func:`PyEval_RestoreThread` is a higher-level function which is always
1518
1568
available (even when threads have not been initialized).
1519
1569
@@ -1773,6 +1823,8 @@ function. You can create and destroy them using the following functions:
1773
1823
haven't been explicitly destroyed at that point.
1774
1824
1775
1825
1826
+ .. _per-interpreter-gil:
1827
+
1776
1828
A Per-Interpreter GIL
1777
1829
---------------------
1778
1830
@@ -1784,7 +1836,7 @@ being blocked by other interpreters or blocking any others. Thus a
1784
1836
single Python process can truly take advantage of multiple CPU cores
1785
1837
when running Python code. The isolation also encourages a different
1786
1838
approach to concurrency than that of just using threads.
1787
- (See :pep:`554`.)
1839
+ (See :pep:`554` and :pep:`684` .)
1788
1840
1789
1841
Using an isolated interpreter requires vigilance in preserving that
1790
1842
isolation. That especially means not sharing any objects or mutable
@@ -2352,12 +2404,20 @@ per-object locks for :term:`free-threaded <free threading>` CPython. They are
2352
2404
intended to replace reliance on the :term:`global interpreter lock`, and are
2353
2405
no-ops in versions of Python with the global interpreter lock.
2354
2406
2407
+ Critical sections are intended to be used for custom types implemented
2408
+ in C-API extensions. They should generally not be used with built-in types like
2409
+ :class:`list` and :class:`dict` because their public C-APIs
2410
+ already use critical sections internally, with the notable
2411
+ exception of :c:func:`PyDict_Next`, which requires critical section
2412
+ to be acquired externally.
2413
+
2355
2414
Critical sections avoid deadlocks by implicitly suspending active critical
2356
- sections and releasing the locks during calls to :c:func:`PyEval_SaveThread`.
2357
- When :c:func:`PyEval_RestoreThread` is called, the most recent critical section
2358
- is resumed, and its locks reacquired. This means the critical section API
2359
- provides weaker guarantees than traditional locks -- they are useful because
2360
- their behavior is similar to the :term:`GIL`.
2415
+ sections, hence, they do not provide exclusive access such as provided by
2416
+ traditional locks like :c:type:`PyMutex`. When a critical section is started,
2417
+ the per-object lock for the object is acquired. If the code executed inside the
2418
+ critical section calls C-API functions then it can suspend the critical section thereby
2419
+ releasing the per-object lock, so other threads can acquire the per-object lock
2420
+ for the same object.
2361
2421
2362
2422
The functions and structs used by the macros are exposed for cases
2363
2423
where C macros are not available. They should only be used as in the
0 commit comments