with_critical_section_mutex

Function with_critical_section_mutex 

Source
pub fn with_critical_section_mutex<F, R, T>(
    _py: Python<'_>,
    mutex: &PyMutex<T>,
    f: F,
) -> R
where F: for<'s> FnOnce(EnteredCriticalSection<'s, T>) -> R,
Expand description

Executes a closure with a Python critical section held on a PyMutex.

Locks the mutex mutex until the closure f finishes. The mutex may be temporarily unlocked and re-acquired if the closure calls back into the interpreter. See the notes in the pyo3::sync::critical_section module documentation for more details.

This variant is particularly useful when paired with a global PyMutex to create a “local GIL” to protect global state in an extension in an analogous manner to the GIL without introducing any deadlock risks or affecting runtime behavior on the GIL-enabled build.

This is structurally equivalent to the use of the paired Py_BEGIN_CRITICAL_SECTION_MUTEX and Py_END_CRITICAL_SECTION C-API macros.

§Safety

The caller must ensure the closure cannot implicitly release the critical section. See the safety notes in the documentation for pyo3::sync::critical_section::EnteredCriticalSection for more details.