yscv_threadpool/section.rs
1//! `PersistentSection` — session-scoped parallel region.
2//!
3//! Step 3 of the fp32 ORT-gap arc. ORT/Eigen's `ParallelSection` sits all
4//! pool workers in a tight spin-loop polling a single `current_loop`
5//! atomic pointer for the duration of one `Session::run()`. Each op's
6//! `parallel_for` becomes a single pointer store + atomic chunk-counter
7//! CAS — no rayon scope creation, no `Box<dyn FnOnce>` allocation, no
8//! condvar wake, no park/unpark round-trip. On Zen 4 this is measured
9//! at ~3 µs/op dispatch vs ~12 µs for rayon fork-join per op.
10//!
11//! ## Design (Session A — 3.1 + 3.2)
12//!
13//! Rather than modify the existing `worker_loop` to poll a section
14//! pointer on every cycle (which would slow down non-section workloads),
15//! the section is expressed as **N special jobs** — one per worker —
16//! each of which runs [`section_worker_loop`] until `active` flips to
17//! false. Main thread submits all N via the pool's existing injector +
18//! wake path, then dispatches work via [`PersistentSection::parallel_for`]
19//! which toggles `current_loop` to point at a caller-stack
20//! [`LoopWorkItem`]. Workers claim chunks via `fetch_add` on the shared
21//! counter, run the trampoline, increment `done_count`. Main thread
22//! participates (runs chunk 0 inline) and blocks until `done_count`
23//! equals `chunks`.
24//!
25//! ## Lifetime & aliasing discipline
26//!
27//! - Section struct lives for the scope of `YscvPool::enter_section`'s
28//! closure; workers hold no `Arc` on it — the backing storage is on
29//! the enter_section stack frame, kept alive by a join-barrier spin
30//! loop on `workers_remaining`.
31//! - `LoopWorkItem` lives on the caller's stack during a single
32//! `parallel_for` call; main thread blocks on `done_count` before
33//! clearing `current_loop`, guaranteeing all workers have finished
34//! their chunk before the `LoopWorkItem` is reclaimed.
35//! - `active` uses `Release`/`Acquire` so workers observe the `false`
36//! transition without further synchronisation.
37
38use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, AtomicUsize, Ordering};
39
40/// Descriptor for one `parallel_for` loop posted inside a
41/// [`PersistentSection`]. Lives on the main-thread stack during
42/// [`PersistentSection::parallel_for`]; workers observe via
43/// `current_loop` pointer.
44///
45/// `exec(ctx, idx)` runs chunk `idx` of the loop. The trampoline
46/// pattern (monomorphised `fn` item + opaque ctx pointer) mirrors
47/// [`JobRef`](crate::JobRef) so the section stays Send+Sync without
48/// requiring a generic parameter on [`PersistentSection`] itself.
49pub(crate) struct LoopWorkItem {
50 /// Trampoline: decodes `ctx` into the loop's closure and invokes
51 /// it with `idx`.
52 exec: unsafe fn(ctx: *const (), idx: usize),
53 /// Opaque pointer to a caller-stack cell holding the closure.
54 ctx: *const (),
55 /// Total chunks in this loop; workers stop claiming when
56 /// `chunk_counter >= total_chunks`.
57 total_chunks: usize,
58}
59
60// SAFETY: `LoopWorkItem` is only accessed by the section's main thread
61// (store into `current_loop`, clear after join) and by workers (read
62// via pointer, call `exec` on a chunk). The main thread blocks on
63// `done_count` before clearing, so the pointee is alive for every
64// worker dereference. `exec` is a `fn` item (statically `'static`).
65// `ctx` points to a caller-stack closure whose lifetime is guarded by
66// the same join barrier.
67#[allow(unsafe_code)]
68unsafe impl Send for LoopWorkItem {}
69#[allow(unsafe_code)]
70unsafe impl Sync for LoopWorkItem {}
71
72/// Session-scoped parallel region. Construct via
73/// [`YscvPool::enter_section`](crate::YscvPool::enter_section). Provides
74/// [`parallel_for`](Self::parallel_for) for the duration of the section;
75/// the section holds all pool workers in the section worker loop.
76pub struct PersistentSection {
77 /// Current loop pointer, or null when idle. Workers read this on
78 /// every iteration; main thread stores it before dispatch and
79 /// clears it after join.
80 current_loop: AtomicPtr<LoopWorkItem>,
81 /// Chunk index claim counter. Workers and main thread
82 /// `fetch_add(1)` to claim the next chunk; once the return
83 /// value ≥ `total_chunks`, nothing left to do.
84 chunk_counter: AtomicUsize,
85 /// Number of chunks that have **finished**. Main thread blocks on
86 /// `done_count >= chunks` before returning from `parallel_for`.
87 done_count: AtomicUsize,
88 /// Number of workers currently in [`section_worker_loop`]. Used as
89 /// entry/exit barrier: main thread waits for this to reach
90 /// `expected_workers` on section enter, and back to 0 on exit.
91 workers_remaining: AtomicUsize,
92 /// Workers observe `false` and exit their loop. Main thread stores
93 /// `false` on section drop.
94 active: AtomicBool,
95 /// spin-lock to serialise concurrent
96 /// `parallel_for` calls from different threads — critical for
97 /// tower-parallel graphs where both branches post loops to the
98 /// same section. Without this, branch A's `current_loop` store
99 /// races with branch B's store, corrupting the work pointer.
100 /// Contention window is microseconds (the duration of one loop),
101 /// so spin-lock is cheaper than Mutex's futex-based park.
102 dispatch_busy: AtomicBool,
103 /// Number of workers currently inside the `loop_ptr` critical
104 /// section (between the increment here and the matching decrement
105 /// on exit). Main thread spin-waits for this to reach 0 after
106 /// storing `current_loop = null` — otherwise a worker that read
107 /// `loop_ptr` right before the clear could dereference a
108 /// destroyed stack-allocated `Ctx<F>` when `parallel_for` returns.
109 inflight_derefs: AtomicUsize,
110 /// Monotonic loop generation. Main thread increments twice per
111 /// `parallel_for`: once at publish (`loop_gen % 2 == 1` while a
112 /// loop is live), once at clear (`loop_gen % 2 == 0` while idle).
113 /// Workers snapshot this on entry and re-check under the
114 /// `inflight_derefs` guard; a mismatch means stack-reuse ABA
115 /// happened (main returned + next loop at the same stack slot)
116 /// and the pointer comparison alone would silently read a
117 /// reinitialised `LoopWorkItem`. With the counter matching,
118 /// `current_loop` still pointing at the same address, and
119 /// `inflight_derefs > 0` blocking main's return, the frame is
120 /// guaranteed alive. Combined invariant retires the 1 % SIGSEGV
121 /// stress flake without falling back to a per-call heap alloc.
122 loop_gen: AtomicU64,
123}
124
125impl PersistentSection {
126 pub(crate) fn new() -> Self {
127 Self {
128 current_loop: AtomicPtr::new(std::ptr::null_mut()),
129 chunk_counter: AtomicUsize::new(0),
130 done_count: AtomicUsize::new(0),
131 workers_remaining: AtomicUsize::new(0),
132 active: AtomicBool::new(true),
133 dispatch_busy: AtomicBool::new(false),
134 inflight_derefs: AtomicUsize::new(0),
135 loop_gen: AtomicU64::new(0),
136 }
137 }
138
139 /// Number of workers currently inside [`section_worker_loop`].
140 /// Main thread uses this for the enter/exit barriers in
141 /// [`YscvPool::enter_section`](crate::YscvPool::enter_section).
142 #[inline]
143 pub(crate) fn workers_remaining_count(&self) -> usize {
144 self.workers_remaining.load(Ordering::Acquire)
145 }
146
147 /// Signal workers to exit the section loop on their next iteration.
148 /// Called from [`YscvPool::enter_section`](crate::YscvPool::enter_section)
149 /// when the user closure returns.
150 #[inline]
151 pub(crate) fn mark_inactive(&self) {
152 self.active.store(false, Ordering::Release);
153 }
154
155 /// Install this section as the thread-local "current section" for
156 /// the returned [`SectionGuard`]'s lifetime. Consumers call
157 /// [`current_section`] and route `par_chunks_mut_dispatch` through
158 /// [`Self::parallel_for`] when the guard is alive.
159 ///
160 /// Returns a `!Send` RAII guard; Drop restores the previous TLS
161 /// value (nested `install_tls` stacks correctly).
162 #[inline]
163 pub fn install_tls(&self) -> SectionGuard<'_> {
164 let prev = CURRENT_SECTION_TLS.with(|cell| {
165 let prev = cell.get();
166 cell.set(self as *const PersistentSection);
167 prev
168 });
169 SectionGuard {
170 prev,
171 _phantom: std::marker::PhantomData,
172 }
173 }
174
175 /// Post a parallel_for loop. Runs `f(0..chunks)` concurrently across
176 /// the section's workers plus the main thread (which runs chunks
177 /// inline between checks). Blocks until every chunk has completed.
178 ///
179 /// Design notes:
180 /// - Zero heap allocation — `Ctx<F>` and `LoopWorkItem` both live
181 /// on the caller's stack frame. Workers observe them via raw
182 /// pointers, guarded by two independent invariants:
183 /// 1. `inflight_derefs`: workers increment before any deref of
184 /// `loop_ptr`; main spin-waits it back to zero after clearing
185 /// `current_loop`, so main cannot return (and the stack frame
186 /// cannot drop) while any worker is mid-deref.
187 /// 2. `loop_gen`: monotonic counter, bumped by main at publish
188 /// and again at clear. Workers snapshot it before the
189 /// `inflight_derefs` bump and re-check under the guard.
190 /// Covers the stack-reuse ABA window where main returns,
191 /// re-enters `parallel_for`, and allocates a new `LoopWorkItem`
192 /// at the same stack address: the pointer match is
193 /// not enough to distinguish "same loop" from "recycled frame
194 /// with different `exec`/`ctx`/`total_chunks` values", but
195 /// `loop_gen` changes across every publish, so the generation
196 /// mismatch makes the worker skip the deref.
197 /// - Condvar/futex-free — workers spin-poll `current_loop`; main
198 /// signals via a pointer store.
199 /// - Main thread participates: claims chunks via `fetch_add` on
200 /// the same counter, amortising the launch latency.
201 pub fn parallel_for<F>(&self, chunks: usize, f: F)
202 where
203 F: Fn(usize) + Send + Sync,
204 {
205 if chunks == 0 {
206 return;
207 }
208
209 // acquire dispatch-busy spin-lock. Concurrent
210 // `parallel_for` calls from different threads (e.g. two
211 // tower-parallel branches) would otherwise race on
212 // `current_loop`. Spin-lock because the critical section is
213 // short (microseconds); futex-park would cost more than it saves.
214 while self
215 .dispatch_busy
216 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
217 .is_err()
218 {
219 // While waiting for the in-flight loop, this thread (often
220 // a worker via `try_run_regular_task`) is doing nothing
221 // useful. Could opportunistically run section chunks here
222 // — but the section-worker-loop path already does that on
223 // the worker side, and the main thread is typically the
224 // contended one, so plain spin is fine.
225 std::hint::spin_loop();
226 }
227 // Guard to release the spin-lock on panic as well as normal
228 // exit — `parallel_for` runs arbitrary closures that may
229 // panic.
230 struct BusyGuard<'a>(&'a AtomicBool);
231 impl Drop for BusyGuard<'_> {
232 fn drop(&mut self) {
233 self.0.store(false, Ordering::Release);
234 }
235 }
236 let _busy_guard = BusyGuard(&self.dispatch_busy);
237
238 struct Ctx<F: Fn(usize)> {
239 f: F,
240 }
241 #[allow(unsafe_code)]
242 unsafe fn trampoline<F: Fn(usize) + Send + Sync>(ctx: *const (), idx: usize) {
243 // SAFETY: `ctx` was constructed as `&Ctx<F> as *const _` in
244 // `parallel_for`. The caller blocks on `done_count` and
245 // `inflight_derefs` before returning, and bumps `loop_gen`
246 // to invalidate any stale observer; together these keep
247 // `Ctx<F>` alive for every dereference. `F: Fn + Sync`
248 // permits concurrent invocation.
249 #[allow(unsafe_code)]
250 let c = unsafe { &*(ctx as *const Ctx<F>) };
251 (c.f)(idx);
252 }
253
254 let ctx = Ctx { f };
255 let work = LoopWorkItem {
256 exec: trampoline::<F>,
257 ctx: &ctx as *const Ctx<F> as *const (),
258 total_chunks: chunks,
259 };
260
261 // Reset per-loop counters BEFORE publishing the loop pointer
262 // so workers never see a stale done_count.
263 self.chunk_counter.store(0, Ordering::Release);
264 self.done_count.store(0, Ordering::Release);
265 // Bump loop_gen BEFORE publishing the pointer. Workers snapshot
266 // this as part of their entry sequence; any worker that observed
267 // a previous generation's pointer will see the new gen on
268 // re-check and skip the deref. Release-ordered so subsequent
269 // `current_loop.store(work, Release)` happens-after this in
270 // other threads' view.
271 self.loop_gen.fetch_add(1, Ordering::Release);
272 // Publish the loop. Workers spin-polling `current_loop` will
273 // observe it on their next Acquire-load iteration.
274 self.current_loop.store(
275 &work as *const LoopWorkItem as *mut LoopWorkItem,
276 Ordering::Release,
277 );
278
279 // Main thread participates — drain chunks via the shared counter.
280 loop {
281 let idx = self.chunk_counter.fetch_add(1, Ordering::AcqRel);
282 if idx >= chunks {
283 break;
284 }
285 // SAFETY: trampoline invariant — `ctx` and `work` are alive
286 // (stack frame held by this function), `exec` is a `fn` item.
287 #[allow(unsafe_code)]
288 unsafe {
289 (work.exec)(work.ctx, idx);
290 }
291 self.done_count.fetch_add(1, Ordering::Release);
292 }
293
294 // Wait for every claimed chunk to finish. Spin — typical wait
295 // is microseconds; condvar would cost more than it saves.
296 let mut spin = 0u32;
297 while self.done_count.load(Ordering::Acquire) < chunks {
298 if spin < 128 {
299 std::hint::spin_loop();
300 spin = spin.saturating_add(1);
301 } else {
302 std::thread::yield_now();
303 }
304 }
305
306 // Clear the loop pointer, then bump loop_gen again so any
307 // worker that still holds the old pointer and is about to
308 // fetch_add `inflight_derefs` will observe a mismatched
309 // generation on its re-check and skip the deref.
310 self.current_loop
311 .store(std::ptr::null_mut(), Ordering::Release);
312 self.loop_gen.fetch_add(1, Ordering::Release);
313
314 // Drain any worker that already passed the gen+pointer
315 // re-check and is inside the `inflight_derefs` guard. Without
316 // this spin the stack-local `work` / `Ctx<F>` would drop under
317 // them when `parallel_for` returns.
318 let mut spin = 0u32;
319 while self.inflight_derefs.load(Ordering::Acquire) > 0 {
320 if spin < 128 {
321 std::hint::spin_loop();
322 spin = spin.saturating_add(1);
323 } else {
324 std::thread::yield_now();
325 }
326 }
327 }
328}
329
330/// Worker-side loop. Submitted to each pool worker when a section
331/// is entered; returns when `section.active` flips to `false`.
332///
333/// when no section chunk is available, the worker
334/// also attempts to pick up a regular task (e.g. a `join_dyn` submit
335/// from tower-parallel). Without this, tower-parallel graphs would
336/// deadlock — all workers in section mode, `join_dyn` submit has no
337/// picker. The `WorkerDispatchCtx` stashed in TLS by `worker_loop`
338/// gives us access to the worker's local deque + shared pool state.
339///
340/// # Safety
341/// - `section` must outlive the loop; enforced by the main thread
342/// spinning on `workers_remaining` before dropping the section.
343/// - `WORKER_DISPATCH_CTX` TLS is set by `worker_loop` for the lifetime
344/// of the worker thread; pointers inside outlive this call.
345#[allow(unsafe_code)]
346pub(crate) unsafe fn section_worker_loop(section: &PersistentSection) {
347 // Signal entry.
348 section.workers_remaining.fetch_add(1, Ordering::Release);
349
350 let mut steal_rng: u32 = 0x9e37_79b1;
351 let mut idle_spins: u32 = 0;
352 while section.active.load(Ordering::Acquire) {
353 let loop_ptr = section.current_loop.load(Ordering::Acquire);
354 if !loop_ptr.is_null() {
355 // Snapshot `loop_gen` BEFORE the `inflight_derefs` bump
356 // so we lock in "the generation that was live when we
357 // observed `loop_ptr`". Any subsequent mismatch on
358 // re-check means main has moved on (cleared, re-published,
359 // possibly at the same stack address) and the pointer we
360 // hold is stale.
361 let observed_gen = section.loop_gen.load(Ordering::Acquire);
362
363 // Enter critical section: bump `inflight_derefs` BEFORE
364 // dereferencing `loop_ptr`. Main thread's `parallel_for`
365 // spins on this counter after clearing `current_loop`, so
366 // the ctx frame is kept alive until we decrement on exit.
367 section.inflight_derefs.fetch_add(1, Ordering::AcqRel);
368
369 // Re-check both the pointer and the generation. Pointer
370 // alone is insufficient because of stack reuse (main
371 // returns + next parallel_for at the same frame address);
372 // the gen counter catches that case. Gen alone is also
373 // insufficient — a null loop_ptr with a matching old gen
374 // is possible if main cleared without re-publishing yet.
375 let loop_ptr2 = section.current_loop.load(Ordering::Acquire);
376 let current_gen = section.loop_gen.load(Ordering::Acquire);
377 if !loop_ptr2.is_null() && loop_ptr2 == loop_ptr && current_gen == observed_gen {
378 // SAFETY: main thread holds the `LoopWorkItem` and
379 // associated `Ctx<F>` alive until `done_count >= chunks`
380 // AND `inflight_derefs == 0`. We incremented above and
381 // re-checked both pointer + generation — main cannot
382 // clear + return while our guard is live AND the gen
383 // is stable.
384 let work = unsafe { &*loop_ptr };
385 let idx = section.chunk_counter.fetch_add(1, Ordering::AcqRel);
386 if idx < work.total_chunks {
387 // SAFETY: trampoline invariant (see LoopWorkItem docs).
388 unsafe {
389 (work.exec)(work.ctx, idx);
390 }
391 section.done_count.fetch_add(1, Ordering::Release);
392 section.inflight_derefs.fetch_sub(1, Ordering::AcqRel);
393 idle_spins = 0;
394 continue;
395 }
396 // All chunks claimed — exit guard and fall through.
397 }
398 section.inflight_derefs.fetch_sub(1, Ordering::AcqRel);
399 }
400
401 // try regular tasks (join_dyn, submit).
402 // When called on a pool worker, `WORKER_DISPATCH_CTX` gives us
403 // access to `find_task` to pick up the submitted task. Outside
404 // a pool worker (e.g. unit tests driving section_worker_loop
405 // directly) the ctx is None — fall through to back-off.
406 // SAFETY: called from section_worker_loop which runs inside a worker_loop frame.
407 if unsafe { try_run_regular_task(&mut steal_rng) } {
408 idle_spins = 0;
409 continue;
410 }
411
412 // No loop + no regular task. Adaptive back-off.
413 if idle_spins < 1024 {
414 std::hint::spin_loop();
415 idle_spins = idle_spins.saturating_add(1);
416 } else {
417 std::thread::yield_now();
418 }
419 }
420
421 // Signal exit. Main thread spins on this reaching 0.
422 section.workers_remaining.fetch_sub(1, Ordering::Release);
423}
424
425/// pick up a regular task from the worker's local
426/// deque / injector / steal-from-peer. Returns `true` if a task was
427/// executed. Only fires when `WORKER_DISPATCH_CTX` is set (i.e. we're
428/// on a pool worker inside `worker_loop`). Caller keeps its own rng
429/// state for the random-victim steal.
430///
431/// # Safety
432/// - `WORKER_DISPATCH_CTX.local` / `.shared` pointers are valid for
433/// the lifetime of the worker's `worker_loop` frame. This function
434/// is only called from `section_worker_loop`, which runs inside
435/// that frame via the section_worker_trampoline dispatch.
436#[allow(unsafe_code)]
437#[inline]
438unsafe fn try_run_regular_task(rng: &mut u32) -> bool {
439 use crate::WORKER_DISPATCH_CTX;
440 let ctx = WORKER_DISPATCH_CTX.with(|c| c.get());
441 let Some(ctx) = ctx else { return false };
442 // SAFETY: pointers are valid for the worker's `worker_loop` frame;
443 // section_worker_loop is only invoked from within that frame.
444 let local = unsafe { &*ctx.local };
445 let shared = unsafe { &*ctx.shared };
446
447 // Drain local deque first.
448 if let Some(task) = local.pop() {
449 unsafe {
450 task.execute();
451 }
452 return true;
453 }
454 // Then injector + peer steal.
455 if let Some(task) = crate::find_task(local, shared, rng, ctx.worker_id, ctx.nworkers) {
456 unsafe {
457 task.execute();
458 }
459 return true;
460 }
461 false
462}
463
464thread_local! {
465 /// Per-thread current section pointer. Null when no section installed.
466 /// Set via [`PersistentSection::install_tls`] (returns a [`SectionGuard`]
467 /// whose `Drop` restores the previous value). Read via
468 /// [`current_section`] from downstream crates (e.g. `yscv-kernels`'s
469 /// `par_chunks_mut_dispatch`) to decide whether to route parallel work
470 /// through the section or fall back to rayon.
471 static CURRENT_SECTION_TLS: std::cell::Cell<*const PersistentSection> =
472 const { std::cell::Cell::new(std::ptr::null()) };
473}
474
475/// RAII guard returned by [`PersistentSection::install_tls`]. Drops the
476/// thread-local pointer back to its previous value (null or an outer
477/// section) on scope exit. Not `Send`: TLS is per-thread.
478pub struct SectionGuard<'a> {
479 prev: *const PersistentSection,
480 _phantom: std::marker::PhantomData<&'a PersistentSection>,
481}
482
483impl Drop for SectionGuard<'_> {
484 fn drop(&mut self) {
485 CURRENT_SECTION_TLS.with(|cell| cell.set(self.prev));
486 }
487}
488
489/// Returns the current thread-local section, if one is installed via
490/// [`PersistentSection::install_tls`]. Used by `yscv-kernels` to route
491/// `par_chunks_mut_dispatch` through [`PersistentSection::parallel_for`]
492/// instead of rayon's fork-join when a session is active.
493///
494/// # Safety (caller discipline)
495/// The `'static` lifetime is a white lie — the returned reference is
496/// only valid while the corresponding [`SectionGuard`] is alive on this
497/// thread. Callers must not stash the reference across points where the
498/// guard could drop. The standard usage pattern (look up, call
499/// `parallel_for`, discard) is safe because the guard is rooted in
500/// `OnnxRunner::run` and outlives every synchronous dispatch.
501#[inline]
502pub fn current_section() -> Option<&'static PersistentSection> {
503 CURRENT_SECTION_TLS.with(|cell| {
504 let p = cell.get();
505 if p.is_null() {
506 None
507 } else {
508 // SAFETY: pointer non-null only while a SectionGuard is
509 // alive; see the caller-discipline note above.
510 #[allow(unsafe_code)]
511 Some(unsafe { &*p })
512 }
513 })
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519 use std::sync::atomic::AtomicU32;
520
521 /// Smoke test: a freshly-constructed section has the expected
522 /// initial state (no active loop, zero counters, active=true).
523 #[test]
524 fn section_initial_state() {
525 let s = PersistentSection::new();
526 assert!(s.current_loop.load(Ordering::Acquire).is_null());
527 assert_eq!(s.chunk_counter.load(Ordering::Acquire), 0);
528 assert_eq!(s.done_count.load(Ordering::Acquire), 0);
529 assert_eq!(s.workers_remaining.load(Ordering::Acquire), 0);
530 assert!(s.active.load(Ordering::Acquire));
531 }
532
533 /// Drive the section from a single main thread — no worker
534 /// threads. `parallel_for` should still complete because the main
535 /// thread participates. Verifies the trampoline dispatch and
536 /// counter bookkeeping on the happy path.
537 #[test]
538 fn parallel_for_single_thread_runs_all_chunks() {
539 let s = PersistentSection::new();
540 let seen = AtomicU32::new(0);
541 s.parallel_for(10, |idx| {
542 let bit = 1u32 << idx;
543 seen.fetch_or(bit, Ordering::Release);
544 });
545 assert_eq!(seen.load(Ordering::Acquire), 0x3FF); // bits 0..9 set
546 // After parallel_for: loop cleared, counters at 10.
547 assert!(s.current_loop.load(Ordering::Acquire).is_null());
548 assert_eq!(s.chunk_counter.load(Ordering::Acquire), 11); // 10 claimed + 1 overflow
549 assert_eq!(s.done_count.load(Ordering::Acquire), 10);
550 }
551
552 /// Verify `section_worker_loop` exits cleanly when `active` flips
553 /// to false. Uses a separate thread as the "worker" and the main
554 /// thread as "driver".
555 #[test]
556 fn worker_loop_exits_on_active_false() {
557 let s = Box::new(PersistentSection::new());
558 let s_ptr: *const PersistentSection = &*s;
559
560 struct SendPtr(*const PersistentSection);
561 impl SendPtr {
562 #[inline]
563 fn ptr(&self) -> *const PersistentSection {
564 self.0
565 }
566 }
567 // SAFETY: test-only wrapper so we can pass a stack pointer into a
568 // spawned thread. Main keeps the Box alive until handle.join().
569 #[allow(unsafe_code)]
570 unsafe impl Send for SendPtr {}
571 let send_ptr = SendPtr(s_ptr);
572
573 let handle = std::thread::spawn(move || {
574 // SAFETY: `s` is Box'd on the main thread's stack and
575 // kept alive until after join() below. `send_ptr.ptr()`
576 // is a method call so Rust 2021 disjoint-capture doesn't
577 // strip the SendPtr wrapper to the raw pointer.
578 #[allow(unsafe_code)]
579 let section = unsafe { &*send_ptr.ptr() };
580 #[allow(unsafe_code)]
581 unsafe {
582 section_worker_loop(section);
583 }
584 });
585
586 // Let the worker enter the loop.
587 while s.workers_remaining.load(Ordering::Acquire) == 0 {
588 std::thread::yield_now();
589 }
590 assert_eq!(s.workers_remaining.load(Ordering::Acquire), 1);
591
592 // Signal exit; worker should observe on next iteration.
593 s.active.store(false, Ordering::Release);
594 handle.join().expect("worker panicked");
595 assert_eq!(s.workers_remaining.load(Ordering::Acquire), 0);
596 }
597
598 /// Full end-to-end: 2 worker threads + main driving a parallel_for
599 /// over 100 chunks. Verifies chunk dispatch works with multiple
600 /// concurrent workers and that done_count always reaches the
601 /// expected value.
602 #[test]
603 fn parallel_for_two_workers_full_dispatch() {
604 let s = Box::new(PersistentSection::new());
605 let s_ptr: *const PersistentSection = &*s;
606
607 struct SendPtr(*const PersistentSection);
608 impl SendPtr {
609 #[inline]
610 fn ptr(&self) -> *const PersistentSection {
611 self.0
612 }
613 }
614 // SAFETY: test-only wrapper — main keeps Box alive until
615 // handle.join() below, so dereferencing from workers is sound.
616 #[allow(unsafe_code)]
617 unsafe impl Send for SendPtr {}
618 #[allow(unsafe_code)]
619 unsafe impl Sync for SendPtr {}
620 let send_ptr = std::sync::Arc::new(SendPtr(s_ptr));
621
622 let handles: Vec<_> = (0..2)
623 .map(|_| {
624 let p = std::sync::Arc::clone(&send_ptr);
625 std::thread::spawn(move || {
626 // SAFETY: see `send_ptr` safety comment above.
627 #[allow(unsafe_code)]
628 let section = unsafe { &*p.ptr() };
629 #[allow(unsafe_code)]
630 unsafe {
631 section_worker_loop(section);
632 }
633 })
634 })
635 .collect();
636
637 while s.workers_remaining.load(Ordering::Acquire) < 2 {
638 std::thread::yield_now();
639 }
640
641 // Drive several loops back-to-back to exercise the
642 // publish/clear cycle multiple times.
643 for _ in 0..5 {
644 let seen = AtomicU32::new(0);
645 s.parallel_for(20, |idx| {
646 seen.fetch_add(idx as u32, Ordering::Release);
647 });
648 // Sum 0..=19 = 190.
649 assert_eq!(seen.load(Ordering::Acquire), 190);
650 }
651
652 s.active.store(false, Ordering::Release);
653 for h in handles {
654 h.join().expect("worker panicked");
655 }
656 assert_eq!(s.workers_remaining.load(Ordering::Acquire), 0);
657 }
658}