Skip to content

Commit 679d64b

Browse files
colesburyAlexWaygooderlend-aasland
authored
Add "how to" for the critical_section Argument Clinic directive. (#1217)
See also python/cpython#111903. --------- Co-authored-by: Alex Waygood <[email protected]> Co-authored-by: Erlend E. Aasland <[email protected]>
1 parent 01cb216 commit 679d64b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

development-tools/clinic.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1955,6 +1955,52 @@ The generated docstring ends up looking like this:
19551955
Return a copy of the code object with new values for the specified fields.
19561956
19571957
1958+
.. _clinic-howto-critical-sections:
1959+
1960+
How to use critical sections with Argument Clinic
1961+
-------------------------------------------------
1962+
1963+
You can use the ``@critical_section`` directive to instruct Argument Clinic to
1964+
wrap the call to the "impl" function in a "Python critical section".
1965+
In builds of CPython without the Global Interpreter Lock ("GIL"),
1966+
critical sections are required in order to achieve
1967+
thread safety without causing deadlocks between threads.
1968+
When a critical section is entered into, a per-object lock associated
1969+
with the first argument of the decorated function is acquired.
1970+
The lock is released on exiting the critical section.
1971+
1972+
Python critical sections are no-ops in builds of CPython with the GIL.
1973+
See :cpy-file:`Include/internal/pycore_critical_section.h`
1974+
and :pep:`PEP 703 <703#python-critical-sections>`
1975+
for more details about critical sections.
1976+
1977+
Example from :cpy-file:`Modules/_io/bufferedio.c`::
1978+
1979+
/*[clinic input]
1980+
@critical_section
1981+
_io._Buffered.close
1982+
[clinic start generated code]*/
1983+
1984+
The generated glue code looks like this:
1985+
1986+
.. code-block:: c
1987+
1988+
static PyObject *
1989+
_io__Buffered_close(buffered *self, PyObject *Py_UNUSED(ignored))
1990+
{
1991+
PyObject *return_value = NULL;
1992+
1993+
Py_BEGIN_CRITICAL_SECTION(self);
1994+
return_value = _io__Buffered_close_impl(self);
1995+
Py_END_CRITICAL_SECTION();
1996+
1997+
return return_value;
1998+
}
1999+
2000+
2001+
.. versionadded:: 3.13
2002+
2003+
19582004
.. _clinic-howto-deprecate-positional:
19592005
.. _clinic-howto-deprecate-keyword:
19602006

0 commit comments

Comments
 (0)