pub async fn monarch_with_gil<F, R>(f: F) -> RExpand description
Async wrapper around Python::attach intended for async call sites.
Why: under high concurrency, many async tasks can simultaneously try to acquire the GIL. Each call blocks the current tokio worker thread, which can cause runtime starvation / apparent deadlocks (nothing else gets polled).
This wrapper serializes GIL acquisition among async callers so at most one tokio
task is blocked in Python::attach at a time, preventing runtime starvation
under GIL contention.
Note: this does not globally prevent other sync code from calling
Python::attach directly. Use this wrapper for Python
interaction that occurs on async hot paths.
§Re-entrancy Safety
This function is re-entrant safe. If called while already inside a monarch_with_gil
or monarch_with_gil_blocking call (e.g., from a Python→Rust callback), it bypasses
the GIL_LOCK to avoid deadlocks.
§Example
let result = monarch_with_gil(|py| {
// Do work with Python GIL
Ok(42)
})
.await?;