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
1 change: 1 addition & 0 deletions pyo3/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions pyo3/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,8 @@ chrono = "0.4"
pyo3-log = "0.13"
log = "0.4"
tracing = "0.1"

# `pthread_atfork`, to recompute the cached main-thread check in forked
# children (`gil::install_fork_handler`).
[target.'cfg(unix)'.dependencies]
libc = "0.2"
3 changes: 3 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ changes go in the root `NEXT_CHANGELOG.md`.
thread other than the main thread no longer re-acquires it every
100 ms to check for signals that only the main thread can receive.
This cuts GIL hand-offs per query when many threads share the GIL.
- `Statement.execute()` remembers per thread whether it runs on the main
thread (recomputed after `fork()`) instead of asking `threading` on every
call.

### Updated

Expand Down
102 changes: 100 additions & 2 deletions pyo3/src/gil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,67 @@
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::PyModule;
use std::cell::Cell;
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::task::{Context, Poll, Waker};
use tokio::runtime::Runtime;

static THREADING: PyOnceLock<Py<PyModule>> = PyOnceLock::new();

/// Incremented in the child after each `fork()`, where the forking thread
/// becomes the main thread, so answers cached before it are recomputed.
static FORK_GENERATION: AtomicU64 = AtomicU64::new(0);

thread_local! {
/// This thread's `on_main_thread` answer and the fork generation it was
/// computed in.
static MAIN_THREAD: Cell<Option<(u64, bool)>> = const { Cell::new(None) };
}

/// Whether `on_main_thread` may cache: only once forks are tracked.
static CACHE_ENABLED: AtomicBool = AtomicBool::new(false);

/// Recompute cached `on_main_thread` answers in forked children. Called
/// once, at module import. Without it (registration failed), every call
/// asks `threading`, as before caching.
pub(crate) fn install_fork_handler() {
#[cfg(unix)]
{
extern "C" fn after_fork_in_child() {
FORK_GENERATION.fetch_add(1, Ordering::Relaxed);
}
static INSTALL: std::sync::Once = std::sync::Once::new();
// SAFETY: registers a handler that only bumps an atomic, which is
// async-signal-safe as `fork()` requires of child handlers.
INSTALL.call_once(|| {
if unsafe { libc::pthread_atfork(None, None, Some(after_fork_in_child)) } == 0 {
CACHE_ENABLED.store(true, Ordering::Relaxed);
}
});
}
#[cfg(not(unix))]
CACHE_ENABLED.store(true, Ordering::Relaxed);
}

/// Whether the calling thread is Python's main thread, the only one that
/// runs signal handlers. Errs towards `true` (a wrong `true` only keeps
/// signal checks on).
///
/// Either id may match: `threading` refreshes the main thread's `ident`
/// after `fork()` but not its `native_id`, while greenlet libraries
/// (gevent, eventlet) patch `get_ident` but not the OS-level `native_id`.
/// The answer only changes for a thread at `fork()`, so it is cached per
/// thread until the next one; asking `threading` costs a few Python calls
/// under the GIL on every `execute()`.
pub(crate) fn on_main_thread(py: Python<'_>) -> bool {
let cache = CACHE_ENABLED.load(Ordering::Relaxed);
let generation = FORK_GENERATION.load(Ordering::Relaxed);
if let (true, Some((cached_generation, main))) = (cache, MAIN_THREAD.get()) {
if cached_generation == generation {
return main;
}
}
let check = || -> PyResult<bool> {
let threading = THREADING
.get_or_try_init(py, || py.import("threading").map(Bound::unbind))?
Expand All @@ -51,7 +98,13 @@ pub(crate) fn on_main_thread(py: Python<'_>) -> bool {
.call_method0("get_native_id")?
.eq(main.getattr("native_id")?)
};
check().unwrap_or(true)
match check() {
Ok(main) => {
MAIN_THREAD.set(Some((generation, main)));
main
}
Err(_) => true,
}
}

/// Drive `fut` to completion, polling it once with the GIL held first and
Expand All @@ -77,10 +130,55 @@ where

#[cfg(test)]
mod tests {
use super::run_ready_first;
use super::{on_main_thread, run_ready_first, FORK_GENERATION, MAIN_THREAD};
use pyo3::prelude::*;
use std::sync::atomic::Ordering;
use std::time::Duration;

#[test]
fn main_thread_answer_is_cached_until_a_fork() {
super::install_fork_handler();
assert!(super::CACHE_ENABLED.load(Ordering::Relaxed));
Python::initialize();
// `threading` takes the thread that imports it first as the main
// thread; the thread spawned below is never that one.
Python::attach(|py| py.import("threading").map(drop)).unwrap();
std::thread::spawn(|| {
Python::attach(|py| {
assert!(!on_main_thread(py));
let (generation, main) = MAIN_THREAD.get().expect("cached");
assert!(!main);
// A stale answer from before a fork is recomputed.
MAIN_THREAD.set(Some((generation, true)));
assert!(on_main_thread(py));
FORK_GENERATION.fetch_add(1, Ordering::Relaxed);
assert!(!on_main_thread(py));
})
})
.join()
.unwrap();
}

#[cfg(unix)]
#[test]
fn forked_children_see_a_new_generation() {
super::install_fork_handler();
let before = FORK_GENERATION.load(Ordering::Relaxed);
// SAFETY: the child only reads an atomic and exits.
match unsafe { libc::fork() } {
0 => unsafe {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
// `>`: another test may bump the counter in parallel.
let bumped = FORK_GENERATION.load(Ordering::Relaxed) > before;
libc::_exit(if bumped { 0 } else { 1 })
},
pid => {
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(pid, &mut status, 0) }, pid);
assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0);
}
}
}

fn runtime() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
Expand Down
1 change: 1 addition & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,6 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> {
// Records still only surface once a customer raises the relevant
// logger's level, so this default-on install is silent until asked.
logging::init_logging(m.py());
gil::install_fork_handler();
Ok(())
}
Loading