Skip to main content

yscv_threadpool/
lib.rs

1//! Custom work-stealing thread pool with priority-aware cold-idle spin.
2//!
3//! Designed to replace `rayon::ThreadPool` in yscv inference hot paths.
4//! On sub-4ms inferences, rayon's park-on-idle policy dominates MT overhead —
5//! the park/unpark round-trip between back-to-back submissions costs hundreds
6//! of nanoseconds per subtask. ORT's Eigen ThreadPool sidesteps this by
7//! holding workers in a cold-idle spin (~300µs) before parking.
8//!
9//! This crate lands the replacement in phases:
10//!   A.1 — skeleton pool with shared `Mutex<VecDeque<Task>>`, `install` API.
11//!   A.2 — per-worker Chase-Lev deques (via `crossbeam-deque`) with
12//!     random-victim work-stealing, still parks on empty.
13//!   **A.3 (current)** — cold-idle spin before park. Workers spin for
14//!     `YSCV_POOL_SPIN_US` microseconds (default 0) watching for new
15//!     work before blocking on the condvar. Back-to-back inferences
16//!     arriving within the spin window skip the park/unpark round-trip.
17//!   A.4 — priority-aware scheduling + big/physical-core affinity.
18//!   A.5 — `ParallelScope` trait + drop-in into `OnnxRunner`.
19//!   A.6 — empirical tuning and default switch decision.
20//!
21//! ## API
22//!
23//! ```no_run
24//! use yscv_threadpool::YscvPool;
25//! let pool = YscvPool::new(6).expect("build pool");
26//! let result = pool.install(|| {
27//!     // Runs on one of the pool's worker threads.
28//!     42
29//! });
30//! assert_eq!(result, 42);
31//! ```
32//!
33//! ## Unsafe policy
34//!
35//! This crate opts **into** `unsafe` (overriding the workspace-wide
36//! `unsafe_code = deny` lint) for the narrow case of extending closure
37//! lifetimes in `install`, matching `rayon::ThreadPool::install`'s
38//! design. Every `unsafe` block carries a `SAFETY:` comment documenting
39//! the invariants that make it sound.
40
41use std::cell::Cell;
42use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
43use std::sync::{Arc, OnceLock};
44use std::thread;
45use std::time::{Duration, Instant};
46
47// Thread-local set on every pool worker at spawn; read by
48// `YscvPool::current_worker_index()`. None for non-pool threads (main,
49// tests, rayon workers). Used by yscv-kernels to detect re-entrant
50// dispatch and avoid nested parallelism that over-subscribes the pool.
51thread_local! {
52    static CURRENT_WORKER: Cell<Option<usize>> = const { Cell::new(None) };
53}
54
55// per-worker dispatch context installed by
56// `worker_loop` before entering the steal/sleep cycle. Used by
57// `section::try_run_regular_task` when a section is active but
58// `current_loop` is empty — instead of spinning idle, the worker
59// attempts to pick up a regular task (e.g. a `join_dyn` submit from
60// tower-parallel) so tower-parallel graphs don't deadlock.
61//
62// The pointers are valid for the duration of `worker_loop` — cleared
63// before the function returns.
64thread_local! {
65    pub(crate) static WORKER_DISPATCH_CTX: Cell<Option<WorkerDispatchCtx>> =
66        const { Cell::new(None) };
67}
68
69#[derive(Clone, Copy)]
70pub(crate) struct WorkerDispatchCtx {
71    pub(crate) local: *const DequeWorker<Task>,
72    pub(crate) shared: *const Shared,
73    pub(crate) worker_id: usize,
74    pub(crate) nworkers: usize,
75}
76
77pub mod affinity;
78mod scope;
79mod section;
80pub use scope::{AmbientRayonScope, ParallelScope};
81pub use section::{PersistentSection, SectionGuard, current_section};
82
83/// `YSCV_POOL_SPIN_US` — microseconds workers spin on empty before parking.
84/// Default 0 — the optimum for fine-grained ONNX inference graphs
85/// (100–200 dispatches/inf, ~10–50µs apart). Spin burns CPU cycles that
86/// steal from the main thread's useful work; zero-spin + park defers to the
87/// OS scheduler, which wakes fast enough via `thread::unpark` (futex). Higher
88/// spin values progressively regress this workload. Raise via
89/// `YSCV_POOL_SPIN_US` for coarse install-per-task patterns where spin pays
90/// off.
91fn spin_us() -> u64 {
92    static CACHED: OnceLock<u64> = OnceLock::new();
93    *CACHED.get_or_init(|| {
94        std::env::var("YSCV_POOL_SPIN_US")
95            .ok()
96            .and_then(|s| s.parse::<u64>().ok())
97            .unwrap_or(0)
98    })
99}
100
101use crossbeam_deque::{Injector, Steal, Stealer, Worker as DequeWorker};
102
103mod job;
104pub(crate) use job::JobRef;
105
106/// Worker task transport. `JobRef` is a 16-byte Copy type: `(fn_ptr,
107/// data_ptr)`. The caller stores the closure/state on its own stack
108/// frame and blocks on a latch/channel until every worker finishes —
109/// zero heap alloc per task. Replaces the pre-A″.4 `Box<dyn FnOnce>`
110/// which cost ~1200 `Box::new` per 6T inference on the tracker.
111type Task = JobRef;
112
113/// Shared state: one global injector queue for incoming submissions, one
114/// stealer per worker so other workers can steal its leftovers, a
115/// shutdown flag, and the lock-free sleep-state machinery.
116///
117/// ## Sleep state machine (A″.2)
118///
119/// Workers transition through THREE states to avoid futex syscalls in the
120/// hot inference path (where dispatches are 10-50 µs apart):
121///
122/// - `Active` (0): running a task, actively stealing, or in the optional
123///   spin window. `submit` never needs to signal an Active worker.
124/// - `Sleepy` (1): "ready to park" — the worker has exhausted one steal
125///   loop and is yield-watching `jobs_event`. If the counter changes
126///   while we're Sleepy, we observe it on the next yield_now iteration
127///   and drop back to Active, fetching the new work. **Critical: no
128///   park/unpark syscall fires in this state.**
129/// - `Sleeping` (2): past the Sleepy watch window; blocked on
130///   `thread::park_timeout`. Only reached when the worker is truly idle
131///   (no new dispatches in ~32 yield iterations ≈ 100 µs+).
132///
133/// ## JobsEventCounter
134///
135/// Packed `AtomicU64` — the rayon-equivalent of their `JobsEventCounter`:
136/// - bits 0..32   — `counter`: incremented by `submit` when `num_sleepy
137///   > 0 && was_empty`. Sleepy workers captured the old value; counter
138///   > inequality tells them new work exists.
139/// - bits 32..48  — `num_sleepy`: count of workers currently in Sleepy.
140/// - bits 48..64  — `num_sleeping`: count of workers actually parked.
141///
142/// The three fields fit in one atomic word so `submit` reads all of them
143/// with a single `load(Acquire)`. Increments to any field use
144/// `fetch_add`/`fetch_sub` with the right stride (`1`, `1 << 32`,
145/// `1 << 48`). Overflow of `counter` is fine — workers compare equality,
146/// and wrap-around only misses a wake when `num_sleepy` workers captured
147/// the exact same pre-wrap value (vanishingly improbable across 2^32
148/// submits).
149const WORKER_ACTIVE: u8 = 0;
150const WORKER_SLEEPY: u8 = 1;
151const WORKER_SLEEPING: u8 = 2;
152
153/// Number of yield-watch iterations a Sleepy worker performs before
154/// transitioning to Sleeping. Chosen so that under tracker-style
155/// fine-grained dispatch (10-50 µs apart), sequential dispatches land
156/// inside the window and the worker never reaches Sleeping. Tunable via
157/// `YSCV_POOL_SLEEPY_ROUNDS` for coarse workloads.
158fn sleepy_rounds() -> u32 {
159    static CACHED: OnceLock<u32> = OnceLock::new();
160    *CACHED.get_or_init(|| {
161        std::env::var("YSCV_POOL_SLEEPY_ROUNDS")
162            .ok()
163            .and_then(|s| s.parse::<u32>().ok())
164            .unwrap_or(32)
165    })
166}
167
168const JOBS_EVENT_COUNTER_MASK: u64 = 0x0000_0000_FFFF_FFFF;
169const JOBS_EVENT_SLEEPY_SHIFT: u32 = 32;
170const JOBS_EVENT_SLEEPY_INC: u64 = 1u64 << JOBS_EVENT_SLEEPY_SHIFT;
171const JOBS_EVENT_SLEEPY_MASK: u64 = 0x0000_FFFF_0000_0000;
172const JOBS_EVENT_SLEEPING_SHIFT: u32 = 48;
173const JOBS_EVENT_SLEEPING_INC: u64 = 1u64 << JOBS_EVENT_SLEEPING_SHIFT;
174const JOBS_EVENT_SLEEPING_MASK: u64 = 0xFFFF_0000_0000_0000;
175
176#[inline]
177const fn unpack_counter(event: u64) -> u32 {
178    (event & JOBS_EVENT_COUNTER_MASK) as u32
179}
180#[inline]
181const fn unpack_sleepy(event: u64) -> u32 {
182    ((event & JOBS_EVENT_SLEEPY_MASK) >> JOBS_EVENT_SLEEPY_SHIFT) as u32
183}
184#[inline]
185const fn unpack_sleeping(event: u64) -> u32 {
186    ((event & JOBS_EVENT_SLEEPING_MASK) >> JOBS_EVENT_SLEEPING_SHIFT) as u32
187}
188
189struct WorkerSleepState {
190    state: AtomicU8,
191    /// Counter value captured when the worker entered Sleepy. When
192    /// `jobs_event.counter != captured_counter`, new work has been posted
193    /// and the worker drops back to Active — no park needed.
194    captured_counter: AtomicU32,
195    /// Set once the worker thread starts; `submit()` uses this to
196    /// `unpark()` a sleeping worker without holding any lock.
197    thread: OnceLock<thread::Thread>,
198}
199
200impl WorkerSleepState {
201    const fn new() -> Self {
202        Self {
203            state: AtomicU8::new(WORKER_ACTIVE),
204            captured_counter: AtomicU32::new(0),
205            thread: OnceLock::new(),
206        }
207    }
208}
209
210struct Shared {
211    injector: Injector<Task>,
212    stealers: Vec<Stealer<Task>>,
213    shutdown: AtomicBool,
214    /// One entry per worker. Lock-free three-state machine.
215    sleep_states: Vec<WorkerSleepState>,
216    /// Packed (counter, num_sleepy, num_sleeping). See module-level
217    /// comment for bit layout. Drives the epoch-based wake that keeps
218    /// fine-grained dispatches syscall-free.
219    jobs_event: AtomicU64,
220}
221
222impl std::fmt::Debug for Shared {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        f.debug_struct("Shared")
225            .field("workers", &self.stealers.len())
226            .field("shutdown", &self.shutdown.load(Ordering::Relaxed))
227            .finish_non_exhaustive()
228    }
229}
230
231/// Thread pool with a fixed number of worker threads. Uses per-worker
232/// Chase-Lev deques (via `crossbeam-deque`) + random-victim work-stealing.
233/// Use [`YscvPool::new`] to construct, [`YscvPool::install`] to run work.
234#[derive(Debug)]
235pub struct YscvPool {
236    shared: Arc<Shared>,
237    workers: Vec<thread::JoinHandle<()>>,
238    nthreads: usize,
239}
240
241impl YscvPool {
242    /// Builds a pool with `nthreads` worker threads. Returns `Err` on
243    /// `nthreads == 0` (rayon also rejects that).
244    pub fn new(nthreads: usize) -> Result<Self, PoolError> {
245        if nthreads == 0 {
246            return Err(PoolError::ZeroThreads);
247        }
248
249        // Create one deque per worker; collect the stealer halves into
250        // `shared.stealers` so everyone can steal from everyone.
251        let mut worker_deques: Vec<DequeWorker<Task>> = Vec::with_capacity(nthreads);
252        let mut stealers: Vec<Stealer<Task>> = Vec::with_capacity(nthreads);
253        for _ in 0..nthreads {
254            let w = DequeWorker::new_fifo();
255            stealers.push(w.stealer());
256            worker_deques.push(w);
257        }
258
259        let sleep_states: Vec<WorkerSleepState> =
260            (0..nthreads).map(|_| WorkerSleepState::new()).collect();
261        let shared = Arc::new(Shared {
262            injector: Injector::new(),
263            stealers,
264            shutdown: AtomicBool::new(false),
265            sleep_states,
266            jobs_event: AtomicU64::new(0),
267        });
268
269        // Resolve CPU affinity once at pool construction. Policy from env,
270        // defaulting to `physical` (avoid SMT siblings on symmetric SMT).
271        let pinning = affinity::resolve_pinning(affinity::policy_from_env(), nthreads);
272
273        // Spawn workers. Each owns a `DequeWorker<Task>` (not Send on its
274        // own, but we move it into the spawned thread immediately).
275        let mut workers = Vec::with_capacity(nthreads);
276        for (worker_id, local) in worker_deques.into_iter().enumerate() {
277            let s = Arc::clone(&shared);
278            let cpu = pinning.get(worker_id).copied();
279            workers.push(thread::spawn(move || {
280                if let Some(cpu_id) = cpu {
281                    affinity::pin_current_thread(cpu_id);
282                }
283                // Publish our Thread handle so the waker path can
284                // `unpark()` us without holding any lock.
285                let _ = s.sleep_states[worker_id].thread.set(thread::current());
286                // Record our index in TLS so `current_worker_index()`
287                // can report it to nested-dispatch check sites.
288                CURRENT_WORKER.with(|c| c.set(Some(worker_id)));
289                worker_loop(worker_id, local, s)
290            }));
291        }
292
293        Ok(Self {
294            shared,
295            workers,
296            nthreads,
297        })
298    }
299
300    /// Number of worker threads in this pool.
301    pub const fn num_threads(&self) -> usize {
302        self.nthreads
303    }
304
305    /// The caller's worker index within this pool (0..num_threads), or
306    /// `None` if called from a thread that isn't one of our workers
307    /// (e.g. the main thread before `install`, a test thread, a rayon
308    /// worker). Mirrors `rayon::current_thread_index()`.
309    ///
310    /// Note: TLS is process-global, so this returns `Some(i)` on a
311    /// yscv-pool worker even when the function is invoked via a
312    /// different `YscvPool` instance — acceptable because kernels use
313    /// this purely to avoid re-entrant dispatch, and any yscv worker
314    /// is by definition busy.
315    pub fn current_worker_index(&self) -> Option<usize> {
316        CURRENT_WORKER.with(|c| c.get())
317    }
318
319    /// Runs `f` on one of the pool's worker threads and blocks the caller
320    /// until it returns. Matches `rayon::ThreadPool::install` semantics —
321    /// the closure may borrow from the caller's stack.
322    ///
323    /// # Safety
324    ///
325    /// The call blocks until the task completes, so any references captured
326    /// in `f` remain valid for the full task lifetime. To fit the closure
327    /// in the shared `Task` queue (`FnOnce + 'static`), we widen its
328    /// lifetime via `transmute`. Same pattern as `rayon::ThreadPool::install`.
329    pub fn install<F, R>(&self, f: F) -> R
330    where
331        F: FnOnce() -> R + Send,
332        R: Send,
333    {
334        // A″.4: zero heap alloc path. The closure + result channel live
335        // on this stack frame via `InstallCell`; we submit a `JobRef`
336        // pointing at it. Caller blocks on `rx.recv()` until the worker
337        // signals, keeping the stack frame alive for the worker's
338        // dereference.
339        let (tx, rx) = std::sync::mpsc::sync_channel::<R>(1);
340        // Put the closure + sender together so the trampoline can
341        // reconstitute them. Wrapped in `ManuallyDrop` because the
342        // trampoline consumes them via `ptr::read` (matches FnOnce
343        // semantics — the closure is moved out before execution).
344        use std::mem::ManuallyDrop;
345        struct InstallCell<F, R: Send>
346        where
347            F: FnOnce() -> R,
348        {
349            f: ManuallyDrop<F>,
350            tx: ManuallyDrop<std::sync::mpsc::SyncSender<R>>,
351        }
352        #[allow(unsafe_code)]
353        unsafe fn install_trampoline<F, R>(data: *const ())
354        where
355            F: FnOnce() -> R + Send,
356            R: Send,
357        {
358            // SAFETY: `data` was `&cell as *const InstallCell<F, R> as
359            // *const ()`. The caller (`install`) is blocked on `rx`
360            // until we finish, so `cell` is alive. We `ptr::read` F
361            // and the sender — one-shot consume, matching FnOnce.
362            #[allow(unsafe_code)]
363            let cell = unsafe { &*(data as *const InstallCell<F, R>) };
364            #[allow(unsafe_code)]
365            let f = unsafe { std::ptr::read(&*cell.f) };
366            #[allow(unsafe_code)]
367            let tx = unsafe { std::ptr::read(&*cell.tx) };
368            let value = f();
369            let _ = tx.send(value);
370        }
371        let cell = InstallCell {
372            f: ManuallyDrop::new(f),
373            tx: ManuallyDrop::new(tx),
374        };
375        // SAFETY: `install_trampoline::<F, R>` is a `fn` item, `'static`
376        // by definition. `&cell` outlives the blocking `rx.recv()` below,
377        // so the worker's dereference is valid. Same lifetime invariant
378        // as the previous Box-based path.
379        #[allow(unsafe_code)]
380        let job = unsafe {
381            JobRef::new(
382                &cell as *const InstallCell<F, R> as *const (),
383                install_trampoline::<F, R>,
384            )
385        };
386        self.submit(job);
387        rx.recv().expect("worker dropped the result channel")
388    }
389
390    /// Internal: push a task onto the global injector and wake workers.
391    ///
392    /// Three-path fast route:
393    /// 1. Load packed `jobs_event` once. If both `num_sleepy == 0` and
394    ///    `num_sleeping == 0` → push and return (everyone is Active,
395    ///    they'll find the task via steal/injector on their next loop).
396    /// 2. If `num_sleepy > 0` → bump the counter. Sleepy workers are
397    ///    yield-watching it and observe the change without any syscall.
398    /// 3. If `num_sleeping > 0` → scan `sleep_states` for a Sleeping
399    ///    worker, CAS it to Active, and `unpark()`.
400    fn submit(&self, task: Task) {
401        self.shared.injector.push(task);
402        self.notify_workers(1);
403    }
404
405    /// Batch notification path used by `par_for_each_index` after
406    /// pushing N helper tasks. A single `fetch_add(N)` on the counter +
407    /// optionally up to `n` unparks wakes at most `n` Sleeping workers
408    /// instead of doing one `submit` per helper with N cascaded atomic
409    /// RMWs. On a graph with hundreds of parallel regions this removes
410    /// thousands of cascaded atomic RMWs per inference.
411    fn notify_workers(&self, job_count: usize) {
412        let event = self.shared.jobs_event.load(Ordering::Acquire);
413        let num_sleepy = unpack_sleepy(event);
414        let num_sleeping = unpack_sleeping(event);
415        if num_sleepy == 0 && num_sleeping == 0 {
416            return;
417        }
418        if num_sleepy > 0 {
419            // Single counter increment per notify — Sleepy workers compare
420            // equality, not delta, so one bump is sufficient even for
421            // multi-task batches. Release pairs with workers' Acquire.
422            self.shared.jobs_event.fetch_add(1, Ordering::Release);
423        }
424        if num_sleeping > 0 {
425            // Wake up to `job_count` Sleeping workers via unpark. Without
426            // this bound, a single submit would wake all sleepers when we
427            // only have one task for them. With it, each futex_wake
428            // corresponds to exactly one available task.
429            let wakes_wanted = job_count.min(num_sleeping as usize);
430            let mut woken = 0usize;
431            for st in &self.shared.sleep_states {
432                if woken >= wakes_wanted {
433                    break;
434                }
435                if st.state.load(Ordering::Relaxed) != WORKER_SLEEPING {
436                    continue;
437                }
438                if st
439                    .state
440                    .compare_exchange(
441                        WORKER_SLEEPING,
442                        WORKER_ACTIVE,
443                        Ordering::AcqRel,
444                        Ordering::Relaxed,
445                    )
446                    .is_ok()
447                {
448                    self.shared
449                        .jobs_event
450                        .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
451                    if let Some(t) = st.thread.get() {
452                        t.unpark();
453                    }
454                    woken += 1;
455                }
456            }
457        }
458    }
459
460    /// Push a batch of tasks onto the injector atomically from the
461    /// caller's perspective (still one-by-one into the lock-free queue,
462    /// but we defer notify to a single atomic update + bounded wake).
463    /// Used by `par_for_each_index` where all helpers share the same
464    /// closure and can be enqueued in one burst.
465    fn submit_batch<I: IntoIterator<Item = Task>>(&self, tasks: I) {
466        let mut count = 0usize;
467        for t in tasks {
468            self.shared.injector.push(t);
469            count += 1;
470        }
471        if count > 0 {
472            self.notify_workers(count);
473        }
474    }
475
476    /// Parallel for-each over `0..count`. Runs `f(index)` on pool workers
477    /// in parallel; blocks until all iterations complete. Equivalent to
478    /// rayon's `(0..count).into_par_iter().for_each(f)`.
479    ///
480    /// Dispatch strategy: **zero `Arc`, no mutex, no condvar**. All shared
481    /// state (the next-index counter and the completion latch) lives on
482    /// this function's stack frame. Helpers receive raw pointers into that
483    /// frame; the function blocks on the latch with a spin→yield loop
484    /// until every helper has finished, guaranteeing the frame outlives
485    /// all accesses. The closure is passed via a `&dyn Fn` trait-object
486    /// pointer — no allocation, no `Arc<ClosureHolder>` layer.
487    ///
488    /// This is the hot path of the pool on inference workloads (100-200
489    /// fine-grained parallel regions per inference). The previous design
490    /// allocated 3 `Arc`s + 1 `Arc<ClosureHolder>` + 4 `Arc::clone`s per
491    /// helper + waited on a `Condvar`. Each of those disappears here; the
492    /// only remaining heap alloc per call is `helpers` `Box`es (required
493    /// by the `Injector<Box<dyn FnOnce>>` task type — addressing that
494    /// would need a custom lock-free queue).
495    ///
496    /// # Safety
497    ///
498    /// This function contains `unsafe` blocks — see the `SAFETY:` comments
499    /// at each site for the invariants. In summary: the function blocks
500    /// on `latch` until every helper decrements it, guaranteeing that
501    /// `next`, `latch`, and the closure `f` all outlive any helper
502    /// access through the raw pointers we hand them.
503    pub fn par_for_each_index<F>(&self, count: usize, f: F)
504    where
505        F: Fn(usize) + Send + Sync,
506    {
507        if count == 0 {
508            return;
509        }
510
511        use std::sync::atomic::AtomicUsize;
512
513        // Stack-allocated shared state. Lives for the duration of this
514        // function's frame. Helpers access via raw pointers.
515        let next = AtomicUsize::new(0);
516
517        // Caller participates — it counts as one puller. Cap helpers at
518        // `count - 1` so we don't oversubscribe workers on tiny counts.
519        let helpers = self.nthreads.min(count.saturating_sub(1));
520
521        // `latch` counts down as each helper exits its loop. Caller waits
522        // until it hits 0. When `helpers == 0` we never touch it.
523        let latch = AtomicUsize::new(helpers);
524
525        // Monomorphized trampoline: `fn(*const (), usize)` — a thin fn
526        // pointer, Send/Sync by value and free of lifetime gymnastics.
527        // The context pointer is `&f as *const F as *const ()`. Each
528        // helper calls `(trampoline)(ctx, idx)` which casts back to
529        // `&F` and invokes. This avoids the `&dyn Fn + '_` fat pointer
530        // and its `F: 'static` bound noise.
531        fn trampoline<F: Fn(usize) + Send + Sync>(ctx: *const (), idx: usize) {
532            // SAFETY: `ctx` was constructed as `&f as *const F as *const ()`
533            // in the parent frame. That frame outlives every call via
534            // the latch/spin invariant documented on the outer function.
535            #[allow(unsafe_code)]
536            let f = unsafe { &*(ctx as *const F) };
537            f(idx);
538        }
539        let f_ctx: *const () = (&f as *const F) as *const ();
540        let f_trampoline: fn(*const (), usize) = trampoline::<F>;
541
542        // All helpers need to see: &AtomicUsize next, &AtomicUsize latch,
543        // and the closure fat pointer. We bundle them in a `Copy`
544        // struct that we mark `Send + Sync` manually — the individual
545        // raw pointers are Send/Sync-safe because of the function-scope
546        // lifetime invariant documented above.
547        #[derive(Clone, Copy)]
548        struct Ptrs {
549            next: *const AtomicUsize,
550            latch: *const AtomicUsize,
551            f_ctx: *const (),
552            f_trampoline: fn(*const (), usize),
553            /// Total index count — embedded here rather than captured by
554            /// the helper trampoline, because trampolines are `fn` items
555            /// (no closure environment).
556            count: usize,
557        }
558        // SAFETY: The pointer fields target data that outlives every
559        // helper task — `next`, `latch`, and the closure `f` all live on
560        // this function's stack frame, which we refuse to exit until
561        // every helper has bumped `latch` down to 0 at the spin-wait
562        // loop at the end of this function. The `AtomicUsize` targets
563        // are race-safe; the closure is `Fn + Sync` so concurrent
564        // invocation is sound. `f_trampoline` is a `fn` item, already
565        // Send+Sync.
566        #[allow(unsafe_code)]
567        unsafe impl Send for Ptrs {}
568        #[allow(unsafe_code)]
569        unsafe impl Sync for Ptrs {}
570
571        // Accessor methods so the spawned closure captures `Ptrs` as a
572        // whole (getting the `unsafe impl Send for Ptrs` stamp) rather
573        // than letting Rust-2021 disjoint field capture strip to the
574        // bare raw pointers, which would fail Send.
575        impl Ptrs {
576            #[inline]
577            const fn next(&self) -> *const AtomicUsize {
578                self.next
579            }
580            #[inline]
581            const fn latch(&self) -> *const AtomicUsize {
582                self.latch
583            }
584            #[inline]
585            fn call(&self, idx: usize) {
586                (self.f_trampoline)(self.f_ctx, idx);
587            }
588        }
589
590        let ptrs = Ptrs {
591            next: &next as *const AtomicUsize,
592            latch: &latch as *const AtomicUsize,
593            f_ctx,
594            f_trampoline,
595            count,
596        };
597
598        // A″.4: all helpers share the same `Ptrs` on the caller's stack
599        // frame; each worker's `JobRef` is just a pair of pointers
600        // (trampoline fn + &ptrs). Zero heap allocations per helper vs
601        // the prior `Box<dyn FnOnce>` path which cost one `Box::new`
602        // each. The trampoline runs the pull-from-counter / call / latch
603        // dec loop inline.
604        #[allow(unsafe_code)]
605        unsafe fn helper_trampoline(data: *const ()) {
606            // SAFETY: `data` was `&ptrs as *const Ptrs as *const ()`.
607            // The caller (`par_for_each_index`) blocks on `latch` until
608            // every helper decrements it, so `ptrs` and everything it
609            // points to remain valid.
610            #[allow(unsafe_code)]
611            let p = unsafe { *(data as *const Ptrs) };
612            // count is encoded in the caller's stack frame via the
613            // trampoline's closure? — no, trampolines can't capture.
614            // We read count via Ptrs (need to add it).
615            loop {
616                // SAFETY: p.next outlives helper via blocking latch.
617                #[allow(unsafe_code)]
618                let idx = unsafe { (*p.next()).fetch_add(1, Ordering::Relaxed) };
619                if idx >= p.count {
620                    break;
621                }
622                p.call(idx);
623            }
624            // SAFETY: p.latch outlives helper via blocking latch.
625            #[allow(unsafe_code)]
626            unsafe {
627                (*p.latch()).fetch_sub(1, Ordering::Release);
628            }
629        }
630
631        // Build `helpers` copies of the same `JobRef` pointing to the
632        // shared `ptrs` cell. Using a Vec<Task> (= Vec<JobRef>, 16 B
633        // each) here — allocation is once per call, amortized across
634        // all helpers; far cheaper than N Box<dyn FnOnce>.
635        // SAFETY: `helper_trampoline` is a `fn` item (`'static`), and
636        // `&ptrs` outlives the blocking spin-wait below. Same invariant
637        // as the previous Box-based path.
638        #[allow(unsafe_code)]
639        let job = unsafe { JobRef::new(&ptrs as *const Ptrs as *const (), helper_trampoline) };
640        let tasks: Vec<Task> = (0..helpers).map(|_| job).collect();
641        self.submit_batch(tasks);
642
643        // Caller participates — drains indices inline until the counter
644        // is exhausted. Handles `helpers == 0` (count == 1) entirely
645        // here: no helpers were spawned, the caller is the only puller.
646        loop {
647            let idx = next.fetch_add(1, Ordering::Relaxed);
648            if idx >= count {
649                break;
650            }
651            f(idx);
652        }
653
654        if helpers == 0 {
655            return;
656        }
657
658        // Spin-yield wait for all helpers to exit their loops. They'll
659        // hit the drained counter almost immediately since the caller
660        // also pulled — this is pure join overhead. No condvar: the
661        // window here is microseconds, parking on a cvar would cost
662        // more than it saves.
663        //
664        // Acquire: pair with the helpers' Release on `latch.fetch_sub`
665        // so we observe their memory writes before returning.
666        let mut spin = 0u32;
667        while latch.load(Ordering::Acquire) != 0 {
668            if spin < 64 {
669                std::hint::spin_loop();
670                spin += 1;
671            } else {
672                std::thread::yield_now();
673            }
674        }
675    }
676
677    /// Fork-join: run `a` and `b` in parallel, return both results.
678    /// Equivalent to `rayon::join(a, b)`. Implemented by submitting `a`
679    /// to the pool and running `b` inline on the caller's thread.
680    ///
681    /// # Safety
682    ///
683    /// Same lifetime-extension rule as `install` — we block on the result
684    /// channel for `a`, and `b` runs synchronously, so both closures'
685    /// captures remain live.
686    pub fn join<A, B, RA, RB>(&self, a: A, b: B) -> (RA, RB)
687    where
688        A: FnOnce() -> RA + Send,
689        B: FnOnce() -> RB + Send,
690        RA: Send,
691        RB: Send,
692    {
693        // A″.4: stack-allocate the `a` closure + its result sender into
694        // a `JoinCell` and submit a zero-alloc `JobRef`.
695        let (tx_a, rx_a) = std::sync::mpsc::sync_channel::<RA>(1);
696        use std::mem::ManuallyDrop;
697        struct JoinCell<A, RA: Send>
698        where
699            A: FnOnce() -> RA,
700        {
701            a: ManuallyDrop<A>,
702            tx: ManuallyDrop<std::sync::mpsc::SyncSender<RA>>,
703        }
704        #[allow(unsafe_code)]
705        unsafe fn join_trampoline<A, RA>(data: *const ())
706        where
707            A: FnOnce() -> RA + Send,
708            RA: Send,
709        {
710            // SAFETY: `data` points to a stack-allocated `JoinCell<A, RA>`
711            // held alive by the caller blocking on `rx_a.recv()` below.
712            #[allow(unsafe_code)]
713            let cell = unsafe { &*(data as *const JoinCell<A, RA>) };
714            #[allow(unsafe_code)]
715            let a = unsafe { std::ptr::read(&*cell.a) };
716            #[allow(unsafe_code)]
717            let tx = unsafe { std::ptr::read(&*cell.tx) };
718            let _ = tx.send(a());
719        }
720        let cell = JoinCell {
721            a: ManuallyDrop::new(a),
722            tx: ManuallyDrop::new(tx_a),
723        };
724        // SAFETY: `join_trampoline::<A, RA>` is a `fn` item (`'static`).
725        // `&cell` outlives the `rx_a.recv()` below. See install for the
726        // same pattern.
727        #[allow(unsafe_code)]
728        let job = unsafe {
729            JobRef::new(
730                &cell as *const JoinCell<A, RA> as *const (),
731                join_trampoline::<A, RA>,
732            )
733        };
734        self.submit(job);
735        // Run b synchronously on this thread. Uses one less worker =
736        // better CPU utilization during small fork-join patterns.
737        let rb = b();
738        let ra = rx_a.recv().expect("worker dropped join channel");
739        (ra, rb)
740    }
741
742    /// enter a session-scoped [`PersistentSection`]. All pool
743    /// workers are held in `section_worker_loop` for the duration of
744    /// `f`; regular `submit` / `install` paths are effectively blocked
745    /// during the section (all workers busy). Each
746    /// [`PersistentSection::parallel_for`] call inside the closure
747    /// dispatches work via a single atomic pointer store + chunk-counter
748    /// CAS — no rayon scope creation, no `Box` alloc, no condvar/futex.
749    ///
750    /// Target: the tracker's ~1.6 ms MT-overhead budget. See
751    /// `reflective-fluttering-backus.md` Step 3 for projection.
752    ///
753    /// # Safety
754    ///
755    /// Section and trampoline context are stack-allocated on this
756    /// function's frame. Main thread spins on `workers_remaining` before
757    /// returning, guaranteeing every worker's `section_worker_loop` has
758    /// exited and released the pointer before the stack frame is freed.
759    pub fn enter_section<R, F>(&self, f: F) -> R
760    where
761        F: FnOnce(&PersistentSection) -> R,
762    {
763        let section = PersistentSection::new();
764
765        // Stack-allocated trampoline context — just the section pointer.
766        // Workers read `section_ptr`, cast back to `&PersistentSection`,
767        // run [`section_worker_loop`].
768        #[repr(C)]
769        struct SectionCtx {
770            section_ptr: *const PersistentSection,
771        }
772        // SAFETY: `SectionCtx` holds a pointer to a stack-rooted
773        // `PersistentSection` which outlives every worker dereference
774        // (main thread blocks on `workers_remaining == 0` before
775        // returning). No shared mutable state beyond the section's own
776        // atomics, which are Send/Sync by construction.
777        #[allow(unsafe_code)]
778        unsafe impl Send for SectionCtx {}
779        #[allow(unsafe_code)]
780        unsafe impl Sync for SectionCtx {}
781
782        #[allow(unsafe_code)]
783        unsafe fn section_worker_trampoline(data: *const ()) {
784            // SAFETY: `data` was constructed as `&ctx as *const _` in
785            // `enter_section`. `ctx` lives on the `enter_section` stack
786            // frame, kept alive by the `workers_remaining` spin barrier.
787            #[allow(unsafe_code)]
788            let ctx = unsafe { &*(data as *const SectionCtx) };
789            #[allow(unsafe_code)]
790            let section = unsafe { &*ctx.section_ptr };
791            // SAFETY: see `section` reference above.
792            #[allow(unsafe_code)]
793            unsafe {
794                section::section_worker_loop(section);
795            }
796        }
797
798        let ctx = SectionCtx {
799            section_ptr: &section as *const PersistentSection,
800        };
801
802        // SAFETY: `section_worker_trampoline` is a `fn` item (`'static`).
803        // `&ctx` outlives every worker dereference by the barrier below.
804        #[allow(unsafe_code)]
805        let job = unsafe {
806            JobRef::new(
807                &ctx as *const SectionCtx as *const (),
808                section_worker_trampoline,
809            )
810        };
811
812        // Submit one copy per worker. JobRef is Copy (16 B), so the
813        // Vec is a cheap dense buffer of identical handles.
814        let tasks: Vec<Task> = (0..self.nthreads).map(|_| job).collect();
815        self.submit_batch(tasks);
816
817        // Entry barrier: wait for every worker to pick up its job and
818        // increment `workers_remaining`. Typical time: <10 µs on Zen 4
819        // (workers already Active or in Sleepy). If any worker is
820        // Sleeping, submit_batch's bounded unpark already kicked it.
821        let expected = self.nthreads;
822        let mut spin = 0u32;
823        while section.workers_remaining_count() < expected {
824            if spin < 256 {
825                std::hint::spin_loop();
826                spin = spin.saturating_add(1);
827            } else {
828                std::thread::yield_now();
829            }
830        }
831
832        let result = f(&section);
833
834        // Signal exit. Workers observe `active == false` on their next
835        // loop iteration and `fetch_sub` workers_remaining.
836        section.mark_inactive();
837
838        // Exit barrier: wait for every worker to exit the section
839        // loop. Workers currently in their back-off yield may take a
840        // few µs to observe the flag.
841        let mut spin = 0u32;
842        while section.workers_remaining_count() > 0 {
843            if spin < 256 {
844                std::hint::spin_loop();
845                spin = spin.saturating_add(1);
846            } else {
847                std::thread::yield_now();
848            }
849        }
850
851        result
852    }
853}
854
855impl Drop for YscvPool {
856    fn drop(&mut self) {
857        // Signal shutdown and wake every worker so they exit cleanly.
858        // Each worker has its own Thread handle; unpark them all to
859        // kick any Sleeping ones out of their futex wait.
860        self.shared.shutdown.store(true, Ordering::Release);
861        for st in &self.shared.sleep_states {
862            if let Some(t) = st.thread.get() {
863                t.unpark();
864            }
865        }
866        for handle in self.workers.drain(..) {
867            let _ = handle.join();
868        }
869    }
870}
871
872/// Worker main loop: run own deque tasks first (LIFO for good cache
873/// locality), fall back to injector global queue, then random-victim
874/// steal. Cold-idle spin on empty for `YSCV_POOL_SPIN_US` µs before
875/// falling through to a condvar park.
876fn worker_loop(worker_id: usize, local: DequeWorker<Task>, shared: Arc<Shared>) {
877    let mut steal_rng_state: u32 = 0x9e37_79b1u32.wrapping_mul(worker_id as u32 + 1);
878    let nworkers = shared.stealers.len();
879    let spin_duration = Duration::from_micros(spin_us());
880    let spin_enabled = spin_duration > Duration::ZERO;
881
882    // stash dispatch context in TLS so
883    // `section::section_worker_loop` can call `find_task` to pick up
884    // regular tasks (e.g. `join_dyn` submits from tower-parallel)
885    // while the worker is ALSO processing section chunks. Without this,
886    // tower-parallel graphs deadlock when all workers are spinning on
887    // `section.current_loop` and `join_dyn` submits a task to the
888    // injector with no available worker to pick it up.
889    WORKER_DISPATCH_CTX.with(|cell| {
890        cell.set(Some(WorkerDispatchCtx {
891            local: &local as *const _,
892            shared: Arc::as_ptr(&shared),
893            worker_id,
894            nworkers,
895        }));
896    });
897    // Guard that clears the TLS on worker exit — RAII so it fires on
898    // both normal return and unwinding paths (worker panic would leave
899    // a dangling pointer otherwise).
900    struct ClearDispatchCtxGuard;
901    impl Drop for ClearDispatchCtxGuard {
902        fn drop(&mut self) {
903            WORKER_DISPATCH_CTX.with(|cell| cell.set(None));
904        }
905    }
906    let _dispatch_ctx_guard = ClearDispatchCtxGuard;
907
908    'outer: loop {
909        // Drain local deque first.
910        while let Some(task) = local.pop() {
911            #[allow(unsafe_code)]
912            unsafe {
913                task.execute();
914            }
915        }
916
917        // Try injector + work-stealing.
918        if let Some(task) = find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers) {
919            #[allow(unsafe_code)]
920            unsafe {
921                task.execute();
922            }
923            continue;
924        }
925
926        if shared.shutdown.load(Ordering::Acquire) {
927            return;
928        }
929
930        // Cold-idle spin (deprecated default: spin_us=0). Still honoured
931        // via env override for callers that want busy-spin instead of
932        // the Sleepy yield-watch below.
933        if spin_enabled {
934            let deadline = Instant::now() + spin_duration;
935            while Instant::now() < deadline {
936                if shared.shutdown.load(Ordering::Acquire) {
937                    return;
938                }
939                if let Some(task) =
940                    find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
941                {
942                    #[allow(unsafe_code)]
943                    unsafe {
944                        task.execute();
945                    }
946                    break;
947                }
948                std::hint::spin_loop();
949            }
950            if let Some(task) =
951                find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
952            {
953                #[allow(unsafe_code)]
954                unsafe {
955                    task.execute();
956                }
957                continue;
958            }
959        }
960
961        // ── Sleepy state (A″.2) ──────────────────────────────────
962        //
963        // Instead of jumping straight to `park`, we enter Sleepy: capture
964        // the current `jobs_event` counter, announce ourselves via the
965        // packed `num_sleepy` field, and yield-watch the counter for
966        // `sleepy_rounds()` iterations. On each iteration we also retry
967        // `find_task` — a submit pushed the job before its counter bump
968        // may be visible already.
969        //
970        // Submit's fast path increments the counter ONLY IF `num_sleepy >
971        // 0`, so our Sleepy announcement is load-bearing: it tells submit
972        // "I'm watching, no syscall needed, just bump the counter". The
973        // counter change propagates via cache coherence in ~50-100 ns —
974        // far cheaper than park/unpark (~1 µs each).
975        let st = &shared.sleep_states[worker_id];
976        let initial_event = shared.jobs_event.load(Ordering::Acquire);
977        let captured = unpack_counter(initial_event);
978        st.captured_counter.store(captured, Ordering::Release);
979        st.state.store(WORKER_SLEEPY, Ordering::Release);
980        shared
981            .jobs_event
982            .fetch_add(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
983
984        let rounds = sleepy_rounds();
985        let mut woken_by_counter = false;
986        // `yield_now` (sched_yield on Linux, ~300 ns) spreads the load
987        // across other runnable threads and — measured — outperforms
988        // tight `spin_loop` here. The bottleneck on tracker workloads
989        // isn't the yield cost, it's the cache-coherence ping-pong on
990        // `jobs_event` if 6 workers hammer the atomic in a tight loop.
991        // yield_now gives the cache line a chance to quiesce between
992        // reads.
993        for _ in 0..rounds {
994            thread::yield_now();
995
996            let cur = unpack_counter(shared.jobs_event.load(Ordering::Acquire));
997            if cur != captured {
998                woken_by_counter = true;
999                break;
1000            }
1001            if shared.shutdown.load(Ordering::Acquire) {
1002                shared
1003                    .jobs_event
1004                    .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1005                st.state.store(WORKER_ACTIVE, Ordering::Release);
1006                return;
1007            }
1008            // Opportunistic find_task — some submits may race the
1009            // counter bump (pushed but counter not yet incremented).
1010            if let Some(task) =
1011                find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers)
1012            {
1013                shared
1014                    .jobs_event
1015                    .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1016                st.state.store(WORKER_ACTIVE, Ordering::Release);
1017                #[allow(unsafe_code)]
1018                unsafe {
1019                    task.execute();
1020                }
1021                continue 'outer;
1022            }
1023        }
1024
1025        // Leave Sleepy. Either the counter moved (woken_by_counter) or we
1026        // exhausted the window (truly idle → go Sleeping).
1027        shared
1028            .jobs_event
1029            .fetch_sub(JOBS_EVENT_SLEEPY_INC, Ordering::Release);
1030        if woken_by_counter {
1031            st.state.store(WORKER_ACTIVE, Ordering::Release);
1032            continue;
1033        }
1034
1035        // ── Sleeping state ───────────────────────────────────────
1036        //
1037        // Truly idle past the Sleepy window. CAS Sleepy → Sleeping; if
1038        // submit raced in and already flipped us to Active, skip the park.
1039        if st
1040            .state
1041            .compare_exchange(
1042                WORKER_SLEEPY,
1043                WORKER_SLEEPING,
1044                Ordering::AcqRel,
1045                Ordering::Acquire,
1046            )
1047            .is_err()
1048        {
1049            // submit flipped us to Active — re-loop.
1050            continue;
1051        }
1052        shared
1053            .jobs_event
1054            .fetch_add(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1055
1056        // Recheck for work + shutdown before parking (closes the race
1057        // where submit pushed work between our Sleepy exit and Sleeping
1058        // entry).
1059        let quick_work = find_task(&local, &shared, &mut steal_rng_state, worker_id, nworkers);
1060        if quick_work.is_some() || shared.shutdown.load(Ordering::Acquire) {
1061            if st
1062                .state
1063                .compare_exchange(
1064                    WORKER_SLEEPING,
1065                    WORKER_ACTIVE,
1066                    Ordering::AcqRel,
1067                    Ordering::Relaxed,
1068                )
1069                .is_ok()
1070            {
1071                shared
1072                    .jobs_event
1073                    .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1074            }
1075            if let Some(task) = quick_work {
1076                #[allow(unsafe_code)]
1077                unsafe {
1078                    task.execute();
1079                }
1080            }
1081            if shared.shutdown.load(Ordering::Acquire) {
1082                return;
1083            }
1084            continue;
1085        }
1086
1087        // Blocking park. submit wakes via unpark; 1 ms timeout is a
1088        // safety net (rarely fires in practice once Sleepy catches the
1089        // fast path).
1090        thread::park_timeout(Duration::from_millis(1));
1091        if st
1092            .state
1093            .compare_exchange(
1094                WORKER_SLEEPING,
1095                WORKER_ACTIVE,
1096                Ordering::AcqRel,
1097                Ordering::Relaxed,
1098            )
1099            .is_ok()
1100        {
1101            shared
1102                .jobs_event
1103                .fetch_sub(JOBS_EVENT_SLEEPING_INC, Ordering::Release);
1104        }
1105        if shared.shutdown.load(Ordering::Acquire) {
1106            return;
1107        }
1108    }
1109}
1110
1111/// Find a task to run: injector first, then steal from a random peer.
1112/// Xorshift32 RNG for the victim pick — avoids a hot shared counter
1113/// while still giving reasonable spread.
1114pub(crate) fn find_task(
1115    local: &DequeWorker<Task>,
1116    shared: &Shared,
1117    rng: &mut u32,
1118    worker_id: usize,
1119    nworkers: usize,
1120) -> Option<Task> {
1121    // Try the injector — pumps a batch into our local deque if full.
1122    loop {
1123        match shared.injector.steal_batch_and_pop(local) {
1124            Steal::Success(t) => return Some(t),
1125            Steal::Empty => break,
1126            Steal::Retry => continue,
1127        }
1128    }
1129
1130    // Random-victim steal.
1131    for _ in 0..(nworkers * 2) {
1132        // xorshift32.
1133        *rng ^= *rng << 13;
1134        *rng ^= *rng >> 17;
1135        *rng ^= *rng << 5;
1136        let victim = (*rng as usize) % nworkers;
1137        if victim == worker_id {
1138            continue;
1139        }
1140        match shared.stealers[victim].steal_batch_and_pop(local) {
1141            Steal::Success(t) => return Some(t),
1142            Steal::Empty => {}
1143            Steal::Retry => {}
1144        }
1145    }
1146    None
1147}
1148
1149/// Errors returned by [`YscvPool::new`].
1150#[derive(Debug, Clone, PartialEq, Eq)]
1151pub enum PoolError {
1152    /// `nthreads == 0`.
1153    ZeroThreads,
1154}
1155
1156impl std::fmt::Display for PoolError {
1157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1158        match self {
1159            PoolError::ZeroThreads => write!(f, "thread count must be > 0"),
1160        }
1161    }
1162}
1163
1164impl std::error::Error for PoolError {}
1165
1166#[cfg(test)]
1167mod tests;