diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 30946d3c..3a38bb6b 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -654,6 +654,7 @@ dependencies = [ "arrow-schema", "chrono", "databricks-sql-kernel", + "libc", "log", "pyo3", "pyo3-log", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index f8ee20dd..48feab00 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -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" diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 713efb4c..3a5b8805 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -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 diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs index 27ca9daa..fab06671 100644 --- a/pyo3/src/gil.rs +++ b/pyo3/src/gil.rs @@ -22,12 +22,49 @@ 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> = 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> = 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). @@ -35,7 +72,17 @@ static THREADING: PyOnceLock> = PyOnceLock::new(); /// 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 { let threading = THREADING .get_or_try_init(py, || py.import("threading").map(Bound::unbind))? @@ -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 @@ -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 { + // `>`: 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) diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 0debe4fa..8a3f9cc3 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -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(()) }