Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add flag to skip reference pool mutex if the program doesn't use the pool #4174

Closed
wants to merge 2 commits into from
Closed
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
27 changes: 23 additions & 4 deletions src/gil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::cell::Cell;
use std::cell::RefCell;
#[cfg(not(debug_assertions))]
use std::cell::UnsafeCell;
use std::sync::atomic::AtomicBool;
use std::{mem, ptr::NonNull, sync};

static START: sync::Once = sync::Once::new();
Expand Down Expand Up @@ -215,6 +216,7 @@ impl GILGuard {
let gstate = unsafe { ffi::PyGILState_Ensure() }; // acquire GIL
#[allow(deprecated)]
let pool = unsafe { mem::ManuallyDrop::new(GILPool::new()) };
update_deferred_reference_counts(pool.python());

Some(GILGuard { gstate, pool })
}
Expand All @@ -238,22 +240,36 @@ type PyObjVec = Vec<NonNull<ffi::PyObject>>;
#[cfg(not(pyo3_disable_reference_pool))]
/// Thread-safe storage for objects which were dec_ref while the GIL was not held.
struct ReferencePool {
ever_used: AtomicBool,
pending_decrefs: sync::Mutex<PyObjVec>,
}

#[cfg(not(pyo3_disable_reference_pool))]
impl ReferencePool {
const fn new() -> Self {
Self {
ever_used: AtomicBool::new(false),
pending_decrefs: sync::Mutex::new(Vec::new()),
}
}

fn register_decref(&self, obj: NonNull<ffi::PyObject>) {
self.ever_used.store(true, sync::atomic::Ordering::Relaxed);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might actually help to even avoid this memory traffic if the flag already is set, e.g.

self.ever_used.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed);

Copy link
Member Author

@davidhewitt davidhewitt May 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing this locally (albeit with a single thread), the .store seems to perform better, so will leave as-is for now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

albeit with a single thread

To be honest, a single-threaded test cannot really tell us anything about the effects of cache line bouncing as there is only a single core's cache involved? (In any case, I would be more keen on the Lazy-based approach than open-coding this.)

self.pending_decrefs.lock().unwrap().push(obj);
}

fn update_counts(&self, _py: Python<'_>) {
#[inline]
fn update_counts(&self, py: Python<'_>) {
// Justification for relaxed: worst case this causes already deferred drops to be
// delayed slightly later, and this is also a one-time flag, so if the program is
// using deferred drops it is highly likely that branch prediction will always
// assume this is true and we don't need the atomic overhead.
if self.ever_used.load(sync::atomic::Ordering::Relaxed) {
self.update_counts_impl(py)
}
}

fn update_counts_impl(&self, _py: Python<'_>) {
let mut pending_decrefs = self.pending_decrefs.lock().unwrap();
if pending_decrefs.is_empty() {
return;
Expand All @@ -268,6 +284,12 @@ impl ReferencePool {
}
}

#[inline]
#[cfg(not(pyo3_disable_reference_pool))]
pub(crate) fn update_deferred_reference_counts(py: Python<'_>) {
POOL.update_counts(py);
}

#[cfg(not(pyo3_disable_reference_pool))]
unsafe impl Sync for ReferencePool {}

Expand Down Expand Up @@ -370,9 +392,6 @@ impl GILPool {
#[inline]
pub unsafe fn new() -> GILPool {
increment_gil_count();
// Update counts of PyObjects / Py that have been cloned or dropped since last acquisition
#[cfg(not(pyo3_disable_reference_pool))]
POOL.update_counts(Python::assume_gil_acquired());
GILPool {
start: OWNED_OBJECTS
.try_with(|owned_objects| {
Expand Down
7 changes: 5 additions & 2 deletions src/impl_/trampoline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ use std::{
#[allow(deprecated)]
use crate::gil::GILPool;
use crate::{
callback::PyCallbackOutput, ffi, ffi_ptr_ext::FfiPtrExt, impl_::panic::PanicTrap,
methods::IPowModulo, panic::PanicException, types::PyModule, Py, PyResult, Python,
callback::PyCallbackOutput, ffi, ffi_ptr_ext::FfiPtrExt, gil::update_deferred_reference_counts,
impl_::panic::PanicTrap, methods::IPowModulo, panic::PanicException, types::PyModule, Py,
PyResult, Python,
};

#[inline]
Expand Down Expand Up @@ -182,6 +183,7 @@ where
#[allow(deprecated)]
let pool = unsafe { GILPool::new() };
let py = pool.python();
update_deferred_reference_counts(py);
let out = panic_result_into_callback_output(
py,
panic::catch_unwind(move || -> PyResult<_> { body(py) }),
Expand Down Expand Up @@ -229,6 +231,7 @@ where
#[allow(deprecated)]
let pool = GILPool::new();
let py = pool.python();
update_deferred_reference_counts(py);
if let Err(py_err) = panic::catch_unwind(move || body(py))
.unwrap_or_else(|payload| Err(PanicException::from_panic_payload(payload)))
{
Expand Down
Loading