Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Doc/c-api/structures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ under :ref:`reference counting <countingrefs>`.
Do not use this field directly; use :c:macro:`Py_TYPE` and
:c:func:`Py_SET_TYPE` instead.

.. c:member:: PyMutex ob_mutex

A per-object lock, present only in the :term:`free-threaded <free threading>`
build (when :c:macro:`Py_GIL_DISABLED` is defined).

This field is **reserved for use by the critical section API**
(:c:macro:`Py_BEGIN_CRITICAL_SECTION` / :c:macro:`Py_END_CRITICAL_SECTION`).
Do **not** lock it directly with ``PyMutex_Lock``; doing so can cause
deadlocks. If you need your own lock, add a separate :c:type:`PyMutex`
field to your object struct.

See :ref:`per-object-locks` in the free-threading extension guide for
details.

.. versionadded:: 3.13


.. c:type:: PyVarObject

Expand Down
24 changes: 24 additions & 0 deletions Doc/howto/free-threading-extensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,30 @@ Important Considerations
internal extension state, standard mutexes or other synchronization
primitives might be more appropriate.

.. _per-object-locks:

Per-Object Locks (``ob_mutex``)
...............................

In the free-threaded build, each Python object contains a :c:member:`~PyObject.ob_mutex`
field of type :c:type:`PyMutex`. This mutex is **reserved for use by the
critical section API** (:c:macro:`Py_BEGIN_CRITICAL_SECTION` /
:c:macro:`Py_END_CRITICAL_SECTION`).

.. warning::

Do **not** lock ``ob_mutex`` directly with ``PyMutex_Lock(&obj->ob_mutex)``.
Mixing direct ``PyMutex_Lock`` calls with the critical section API on the
same mutex can cause deadlocks.

Even if your own code never uses critical sections on a particular object type,
**CPython internals may use the critical section API on any Python object**.

If your extension type needs its own lock, add a separate :c:type:`PyMutex`
field (or another synchronization primitive) to your object struct.
:c:type:`PyMutex` is very lightweight, so there is negligible cost to having
an additional one.


Building Extensions for the Free-Threaded Build
===============================================
Expand Down
Loading