Skip to content

Commit 83d1ce4

Browse files
add cases where cs can be suspended
1 parent 801cf3f commit 83d1ce4

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

Doc/c-api/init.rst

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2299,12 +2299,33 @@ per-object locks for :term:`free-threaded <free threading>` CPython. They are
22992299
intended to replace reliance on the :term:`global interpreter lock`, and are
23002300
no-ops in versions of Python with the global interpreter lock.
23012301
2302+
Critical sections are intended to be used for custom types implemented
2303+
in C-API extensions. They should generally not be used with built-in types like
2304+
:class:`list` and :class:`dict` because their public C-APIs
2305+
already use critical sections internally, with the :ref:`notable
2306+
exception<PyDict_Next>` of :c:func:`PyDict_Next`, which requires critical section
2307+
to be acquired externally.
2308+
23022309
Critical sections avoid deadlocks by implicitly suspending active critical
2303-
sections and releasing the locks during calls to :c:func:`PyEval_SaveThread`.
2304-
When :c:func:`PyEval_RestoreThread` is called, the most recent critical section
2305-
is resumed, and its locks reacquired. This means the critical section API
2306-
provides weaker guarantees than traditional locks -- they are useful because
2307-
their behavior is similar to the :term:`GIL`.
2310+
sections, hence, they do not provide exclusive access such as provided by
2311+
traditional locks like :c:type:`PyMutex`. When a critical section is started,
2312+
the per-object lock for the object is acquired. If the code executed inside the
2313+
critical section suspends the critical section, the per-object lock is released,
2314+
so other threads can acquire the per-object lock for the same object.
2315+
2316+
The critical sections can be suspended in the following situations:
2317+
2318+
* Calling back into Python code, such as calling a Python function or method.
2319+
2320+
* Calling any C API function which internally uses critical sections
2321+
such as :c:func:`PyList_Append` or :c:func:`PyDict_SetItem`.
2322+
2323+
* Locking of :c:type:`PyMutex` by :c:func:`PyMutex_Lock`.
2324+
2325+
* Calling :c:func:`PyEval_SaveThread` to detach the current thread.
2326+
2327+
* Recursively entering the critical section for the same object.
2328+
23082329
23092330
Variants that accept :c:type:`PyMutex` pointers rather than Python objects are also
23102331
available. Use these variants to start a critical section in a situation where

0 commit comments

Comments
 (0)