1#[cfg(all(feature = "fuzz", dst))]
5pub use deterministic::*;
6#[cfg(not(all(feature = "fuzz", dst)))]
7pub use rayon::{
8 current_num_threads, current_thread_index, in_place_scope, join, scope, spawn, spawn_fifo,
9 BroadcastContext, Scope, ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder,
10};
11
12#[cfg(all(feature = "fuzz", dst))]
13mod deterministic {
14 use crate::sync::deterministic::{with_pool_slots, Waiter};
15 use shuttle::{
16 sync::{mpsc, Mutex},
17 thread, thread_local,
18 };
19 use std::{
20 any::Any,
21 cell::RefCell,
22 error::Error,
23 fmt, mem,
24 panic::{catch_unwind, resume_unwind, AssertUnwindSafe},
25 sync::{
26 atomic::{AtomicUsize, Ordering},
27 Arc, OnceLock,
28 },
29 };
30
31 #[allow(
32 clippy::disallowed_types,
33 clippy::disallowed_methods,
34 reason = "Native identities outlive executions; pool occupancy and waiters are execution-local."
35 )]
36 static NEXT_POOL: AtomicUsize = AtomicUsize::new(1);
37 #[allow(
38 clippy::disallowed_types,
39 clippy::disallowed_methods,
40 reason = "Native storage retains only pool configuration; scheduling state is execution-local."
41 )]
42 static GLOBAL_POOL: OnceLock<ThreadPool> = OnceLock::new();
43
44 thread_local! {
45 static CONTEXT: RefCell<Option<WorkerContext>> = RefCell::new(None);
46 }
47
48 type Panic = Box<dyn Any + Send + 'static>;
49 type PanicHandler = Arc<dyn Fn(Panic) + Send + Sync>;
50 type Job<'env> = Box<dyn FnOnce(&Scope<'env>) + Send + 'env>;
51
52 #[derive(Clone)]
54 pub struct ThreadPool {
55 id: usize,
56 names: Arc<Vec<Option<String>>>,
57 panic_handler: Option<PanicHandler>,
58 }
59
60 impl ThreadPool {
61 pub fn current_num_threads(&self) -> usize {
63 self.names.len()
64 }
65
66 pub fn current_thread_index(&self) -> Option<usize> {
68 CONTEXT.with(|context| {
69 context
70 .borrow()
71 .as_ref()
72 .filter(|c| c.pool.id == self.id && c.owns_slot)
73 .map(|c| c.index)
74 })
75 }
76
77 pub fn install<T: Send>(&self, f: impl FnOnce() -> T + Send) -> T {
82 if self.current_thread_index().is_some() {
83 f()
84 } else {
85 without_current_slot(|| {
86 thread::scope(|threads| {
87 let result = threads
88 .spawn(|| catch_unwind(AssertUnwindSafe(|| self.execute(None, f))))
89 .join()
90 .unwrap_or_else(|panic| resume_unwind(panic));
91 result.unwrap_or_else(|panic| resume_unwind(panic))
92 })
93 })
94 }
95 }
96
97 pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {
99 let pool = self.clone();
100 let handle = thread::Builder::new()
101 .name(self.names[0].clone().unwrap_or_else(|| "compute".into()))
102 .spawn(move || {
103 pool.execute(None, || {
104 if let Err(panic) = catch_unwind(AssertUnwindSafe(f)) {
105 if let Some(handler) = &pool.panic_handler {
106 handler(panic);
107 } else {
108 resume_unwind(panic);
109 }
110 }
111 });
112 })
113 .expect("Shuttle logical thread creation is infallible");
114 drop(handle);
115 }
116
117 pub fn spawn_fifo(&self, f: impl FnOnce() + Send + 'static) {
119 self.spawn(f);
120 }
121
122 pub fn broadcast<T: Send>(&self, f: impl Fn(BroadcastContext<'_>) -> T + Sync) -> Vec<T> {
124 without_current_slot(|| {
125 let results = scope_inner(None, |scope| {
126 let (sender, receiver) = mpsc::channel();
127 let f = &f;
128 for index in 0..self.current_num_threads() {
129 let sender = sender.clone();
130 scope.spawn(move |_| {
131 let result = self
132 .execute(Some(index), || f(BroadcastContext { pool: self, index }));
133 sender.send((index, result)).unwrap_or_else(|_| {
134 panic!("broadcast receiver outlives callbacks")
135 });
136 });
137 }
138 drop(sender);
139 receiver.into_iter().collect::<Vec<_>>()
140 });
141 let mut results = results;
142 results.sort_unstable_by_key(|(index, _)| *index);
143 results.into_iter().map(|(_, result)| result).collect()
144 })
145 }
146
147 pub fn in_place_scope<'env, T>(&self, f: impl FnOnce(&Scope<'env>) -> T) -> T {
152 scope_inner(Some(self.clone()), f)
153 }
154
155 pub fn scope<'env, T: Send>(&self, f: impl FnOnce(&Scope<'env>) -> T + Send) -> T {
159 self.install(|| self.in_place_scope(f))
160 }
161
162 pub const fn id(&self) -> usize {
164 self.id
165 }
166
167 fn execute<T>(&self, index: Option<usize>, f: impl FnOnce() -> T) -> T {
168 let index = self.acquire(index);
169 let _lease = Lease { pool: self.clone(), index };
170 WorkerContext { pool: self.clone(), index, owns_slot: true }.with(f)
171 }
172
173 fn acquire(&self, index: Option<usize>) -> usize {
174 let waiter = Waiter::new();
176 loop {
177 let available = with_pool_slots(self.id, self.current_num_threads(), |slots| {
178 let available = match index {
179 Some(index) => (!slots.occupied[index]).then_some(index),
180 None => slots.occupied.iter().position(|occupied| !occupied),
181 };
182 if let Some(index) = available {
183 slots.occupied[index] = true;
184 } else {
185 slots.waiters.push(waiter.clone());
186 }
187 available
188 });
189 if let Some(index) = available {
190 return index;
191 }
192 waiter.wait();
193 }
194 }
195
196 fn release(&self, index: usize) {
197 let waiters = with_pool_slots(self.id, self.current_num_threads(), |slots| {
198 slots.occupied[index] = false;
199 mem::take(&mut slots.waiters)
200 });
201 for waiter in waiters {
202 waiter.notify();
203 }
204 }
205
206 fn current() -> Option<Self> {
207 CONTEXT.with(|context| context.borrow().as_ref().map(|context| context.pool.clone()))
208 }
209
210 #[allow(
211 clippy::disallowed_methods,
212 reason = "Global pool configuration is shared across executions, not used to schedule or wait for work."
213 )]
214 fn global() -> Self {
215 GLOBAL_POOL
216 .get_or_init(|| {
217 ThreadPoolBuilder::new()
218 .build()
219 .expect("logical pool construction is infallible")
220 })
221 .clone()
222 }
223 }
224
225 impl fmt::Debug for ThreadPool {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.debug_struct("ThreadPool")
228 .field("num_threads", &self.current_num_threads())
229 .finish_non_exhaustive()
230 }
231 }
232
233 #[derive(Default)]
235 pub struct ThreadPoolBuilder {
236 num_threads: usize,
237 thread_name: Option<Box<dyn FnMut(usize) -> String + Send>>,
238 panic_handler: Option<PanicHandler>,
239 }
240
241 impl ThreadPoolBuilder {
242 pub fn new() -> Self {
244 Self::default()
245 }
246 pub const fn num_threads(mut self, threads: usize) -> Self {
250 self.num_threads = threads;
251 self
252 }
253 pub fn thread_name(mut self, name: impl FnMut(usize) -> String + Send + 'static) -> Self {
259 self.thread_name = Some(Box::new(name));
260 self
261 }
262 pub fn panic_handler(mut self, handler: impl Fn(Panic) + Send + Sync + 'static) -> Self {
264 self.panic_handler = Some(Arc::new(handler));
265 self
266 }
267 #[allow(
270 clippy::disallowed_methods,
271 reason = "Only process-wide pool configuration is stored here; scheduling state is execution-local."
272 )]
273 pub fn build_global(self) -> Result<(), ThreadPoolBuildError> {
274 if GLOBAL_POOL.get().is_some() {
275 return Err(ThreadPoolBuildError::GlobalPoolAlreadyInitialized);
276 }
277 let pool = self.build()?;
280 GLOBAL_POOL.set(pool).map_err(|_| ThreadPoolBuildError::GlobalPoolAlreadyInitialized)
281 }
282 pub fn build(mut self) -> Result<ThreadPool, ThreadPoolBuildError> {
284 let names = (0..self.num_threads.max(1).min(rayon::max_num_threads()))
285 .map(|index| self.thread_name.as_mut().map(|name| name(index)))
286 .collect();
287 Ok(ThreadPool {
288 id: NEXT_POOL.fetch_add(1, Ordering::Relaxed),
289 names: Arc::new(names),
290 panic_handler: self.panic_handler,
291 })
292 }
293 }
294
295 impl fmt::Debug for ThreadPoolBuilder {
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 f.debug_struct("ThreadPoolBuilder")
298 .field("num_threads", &self.num_threads)
299 .finish_non_exhaustive()
300 }
301 }
302
303 #[derive(Debug)]
305 pub enum ThreadPoolBuildError {
306 GlobalPoolAlreadyInitialized,
308 }
309 impl fmt::Display for ThreadPoolBuildError {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 f.write_str("the global compute pool is already initialized")
312 }
313 }
314 impl Error for ThreadPoolBuildError {}
315
316 #[derive(Debug)]
318 pub struct BroadcastContext<'pool> {
319 pool: &'pool ThreadPool,
320 index: usize,
321 }
322 impl BroadcastContext<'_> {
323 pub const fn index(&self) -> usize {
325 self.index
326 }
327 pub fn num_threads(&self) -> usize {
329 self.pool.current_num_threads()
330 }
331 }
332
333 pub struct Scope<'env> {
335 sender: mpsc::Sender<Message<'env>>,
336 }
337 impl<'env> Scope<'env> {
338 pub fn spawn(&self, f: impl FnOnce(&Self) + Send + 'env) {
340 self.sender
341 .send(Message::Job(Box::new(f)))
342 .unwrap_or_else(|_| panic!("scope dispatcher outlives its jobs"));
343 }
344 }
345 impl fmt::Debug for Scope<'_> {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 f.debug_struct("Scope").finish_non_exhaustive()
348 }
349 }
350
351 enum Message<'env> {
352 Job(Job<'env>),
353 Done,
354 }
355 struct Lease {
356 pool: ThreadPool,
357 index: usize,
358 }
359 impl Drop for Lease {
360 fn drop(&mut self) {
361 self.pool.release(self.index);
362 }
363 }
364 #[derive(Clone)]
365 struct WorkerContext {
366 pool: ThreadPool,
367 index: usize,
368 owns_slot: bool,
369 }
370 struct RestoreContext(Option<WorkerContext>);
371 impl Drop for RestoreContext {
372 fn drop(&mut self) {
373 CONTEXT.with(|context| context.replace(self.0.take()));
374 }
375 }
376 impl WorkerContext {
377 fn with<T>(self, f: impl FnOnce() -> T) -> T {
378 let _restore = RestoreContext(CONTEXT.with(|slot| slot.replace(Some(self))));
379 f()
380 }
381 }
382 struct ResumeSlot(WorkerContext);
383 impl Drop for ResumeSlot {
384 fn drop(&mut self) {
385 self.0.pool.acquire(Some(self.0.index));
386 CONTEXT.with(|context| {
387 context
388 .borrow_mut()
389 .as_mut()
390 .expect("suspended context remains installed")
391 .owns_slot = true;
392 });
393 }
394 }
395 fn without_current_slot<T>(f: impl FnOnce() -> T) -> T {
396 let context = CONTEXT.with(|slot| {
397 let mut slot = slot.borrow_mut();
398 slot.as_mut().filter(|context| context.owns_slot).map(|context| {
399 context.owns_slot = false;
400 context.clone()
401 })
402 });
403 let _resume = context.map(|context| {
404 context.pool.release(context.index);
405 ResumeSlot(context)
406 });
407 f()
408 }
409
410 pub fn in_place_scope<'env, T>(f: impl FnOnce(&Scope<'env>) -> T) -> T {
412 scope_inner(Some(ThreadPool::current().unwrap_or_else(ThreadPool::global)), f)
413 }
414
415 fn scope_inner<'env, T>(pool: Option<ThreadPool>, f: impl FnOnce(&Scope<'env>) -> T) -> T {
416 let (sender, receiver) = mpsc::channel();
417 let scope = Scope { sender };
418 let first_panic = Mutex::new(None);
419 let result = thread::scope(|threads| {
420 let scope = &scope;
421 let first_panic = &first_panic;
422 let dispatcher = threads.spawn(move || {
423 let mut running = 1usize;
424 while running != 0 {
425 match receiver.recv().expect("scope sender outlives dispatcher") {
426 Message::Job(job) => {
427 running += 1;
428 let pool = pool.clone();
429 threads.spawn(move || {
430 let execute = || {
431 if let Err(panic) =
432 catch_unwind(AssertUnwindSafe(|| job(scope)))
433 {
434 record_scope_panic(first_panic, panic);
435 }
436 };
437 if let Some(pool) = pool {
438 pool.execute(None, execute);
439 } else {
440 execute();
441 }
442 scope
443 .sender
444 .send(Message::Done)
445 .unwrap_or_else(|_| panic!("scope dispatcher drains all jobs"));
446 });
447 }
448 Message::Done => running -= 1,
449 }
450 }
451 });
452 let result = match catch_unwind(AssertUnwindSafe(|| f(scope))) {
453 Ok(value) => Some(value),
454 Err(panic) => {
455 record_scope_panic(first_panic, panic);
456 None
457 }
458 };
459 scope
460 .sender
461 .send(Message::Done)
462 .unwrap_or_else(|_| panic!("scope dispatcher drains root completion"));
463 without_current_slot(|| {
464 dispatcher.join().unwrap_or_else(|panic| resume_unwind(panic));
465 });
466 result
467 });
468 if let Some(panic) =
469 first_panic.into_inner().unwrap_or_else(|poisoned| poisoned.into_inner())
470 {
471 resume_unwind(panic);
472 }
473 result.expect("scope callback returned when no panic was recorded")
474 }
475
476 fn record_scope_panic(first_panic: &Mutex<Option<Panic>>, panic: Panic) {
477 let mut first = first_panic.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
478 if first.is_none() {
479 *first = Some(panic);
480 } else {
481 drop(first);
484 discard_panic(panic);
485 }
486 }
487
488 pub fn scope<'env, T: Send>(f: impl FnOnce(&Scope<'env>) -> T + Send) -> T {
490 ThreadPool::current().unwrap_or_else(ThreadPool::global).scope(f)
491 }
492 pub fn current_num_threads() -> usize {
494 ThreadPool::current().unwrap_or_else(ThreadPool::global).current_num_threads()
495 }
496 pub fn current_pool_id() -> Option<usize> {
498 CONTEXT.with(|context| context.borrow().as_ref().filter(|c| c.owns_slot).map(|c| c.pool.id))
499 }
500 pub fn current_thread_index() -> Option<usize> {
502 CONTEXT.with(|context| context.borrow().as_ref().filter(|c| c.owns_slot).map(|c| c.index))
503 }
504 pub fn spawn(f: impl FnOnce() + Send + 'static) {
506 ThreadPool::current().unwrap_or_else(ThreadPool::global).spawn(f);
507 }
508 pub fn spawn_fifo(f: impl FnOnce() + Send + 'static) {
510 spawn(f);
511 }
512 pub fn join<A: Send, B: Send>(
514 a: impl FnOnce() -> A + Send,
515 b: impl FnOnce() -> B + Send,
516 ) -> (A, B) {
517 let (sender, receiver) = mpsc::channel();
518 let a = scope(|scope| {
519 scope.spawn(move |_| {
520 let result = catch_unwind(AssertUnwindSafe(b));
521 sender.send(result).unwrap_or_else(|_| panic!("join receiver outlives producer"));
522 });
523 catch_unwind(AssertUnwindSafe(a))
524 });
525 let b = receiver.recv().expect("join producer completed before scope returned");
526 match (a, b) {
527 (Ok(a), Ok(b)) => (a, b),
528 (Err(a), b) => {
529 if let Err(b) = b {
530 discard_panic(b);
531 }
532 resume_unwind(a)
533 }
534 (Ok(_), Err(b)) => resume_unwind(b),
535 }
536 }
537
538 fn discard_panic(panic: Panic) {
539 if let Err(panic) = catch_unwind(AssertUnwindSafe(|| drop(panic))) {
540 mem::forget(panic);
542 }
543 }
544
545 #[cfg(test)]
546 mod tests {
547 use super::*;
548 use crate::sync::Runtime;
549 use shuttle::sync::Barrier;
550 use std::time::Duration;
551
552 #[test]
553 fn retained_pool_isolated_between_concurrent_executions() {
554 assert_concurrent_executions(ThreadPoolBuilder::new().num_threads(2).build().unwrap());
555 }
556
557 #[test]
558 fn global_pool_isolated_between_concurrent_executions() {
559 assert_concurrent_executions(ThreadPool::global());
560 }
561
562 #[test]
563 fn retained_pool_reusable_between_executions() {
564 #[allow(
566 clippy::disallowed_types,
567 reason = "Counts panic callbacks across separate simulations, not execution-local scheduling state."
568 )]
569 let handled = Arc::new(AtomicUsize::new(0));
570 let handler = handled.clone();
571 let pool = ThreadPoolBuilder::new()
572 .num_threads(2)
573 .thread_name(|index| format!("retained-{index}"))
574 .panic_handler(move |panic| {
575 assert_eq!(panic.downcast_ref::<&str>(), Some(&"retained job panicked"));
576 handler.fetch_add(1, Ordering::SeqCst);
577 })
578 .build()
579 .unwrap();
580 let id = pool.id();
581 for expected in 1..=3 {
582 let pool = pool.clone();
583 let handled = handled.clone();
584 Runtime::new().run(move || {
585 assert_eq!(pool.id(), id);
586 assert_eq!(pool.broadcast(|context| context.index()), [0, 1]);
587 let (sender, receiver) = mpsc::channel();
588 pool.spawn(move || {
589 sender.send(thread::current().name().map(str::to_owned)).unwrap();
590 });
591 assert_eq!(receiver.recv().unwrap().as_deref(), Some("retained-0"));
592 pool.spawn(|| panic!("retained job panicked"));
593 for _ in 0..10 {
594 if handled.load(Ordering::SeqCst) == expected {
595 break;
596 }
597 thread::yield_now();
598 }
599 assert_eq!(handled.load(Ordering::SeqCst), expected);
600 });
601 }
602 }
603
604 #[test]
605 fn pool_capacity_shared_and_released_on_unwind() {
606 let pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
607 Runtime::new().run(move || {
608 let mut waiter = None;
609 let panic = catch_unwind(AssertUnwindSafe(|| {
610 pool.install(|| {
611 let contender = pool.clone();
612 waiter = Some(thread::spawn(move || {
613 contender.install(|| contender.current_thread_index())
614 }));
615 wait_for_slot_waiter(&pool);
616 panic!("slot owner panicked");
617 });
618 }))
619 .unwrap_err();
620 assert_eq!(panic.downcast_ref::<&str>(), Some(&"slot owner panicked"));
621 assert_eq!(waiter.unwrap().join().unwrap(), Some(0));
622 with_pool_slots(pool.id(), 1, |slots| {
623 assert_eq!(slots.occupied, [false]);
624 assert!(slots.waiters.is_empty());
625 });
626 });
627 }
628
629 #[test]
630 fn retained_pool_reusable_after_execution_panic() {
631 let pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
632 let failed_pool = pool.clone();
633 let panic = catch_unwind(AssertUnwindSafe(|| {
634 Runtime::new().run(move || {
635 let (sender, receiver) = mpsc::channel();
636 failed_pool.spawn(move || {
637 sender.send(()).unwrap();
638 thread::park();
639 });
640 receiver.recv().unwrap();
641 failed_pool.spawn(|| {});
642 wait_for_slot_waiter(&failed_pool);
643 panic!("runtime workload panicked");
644 });
645 }))
646 .unwrap_err();
647 assert_eq!(panic.downcast_ref::<&str>(), Some(&"runtime workload panicked"));
648 Runtime::new().run(move || {
649 with_pool_slots(pool.id(), 1, |slots| {
650 assert_eq!(slots.occupied, [false]);
651 assert!(slots.waiters.is_empty());
652 });
653 assert_eq!(pool.broadcast(|context| context.index()), [0]);
654 });
655 }
656
657 #[allow(
658 clippy::disallowed_types,
659 clippy::disallowed_methods,
660 reason = "Host channels and lock coordinate two independent simulations, not logical workers within one simulation."
661 )]
662 fn assert_concurrent_executions(pool: ThreadPool) {
663 let threads = pool.current_num_threads();
664 let first_pool = pool.clone();
665 let (entered, entering) = std::sync::mpsc::channel();
666 let (release, releasing) = std::sync::mpsc::channel();
667 let first = std::thread::spawn(move || {
668 Runtime::new().run(move || {
669 let occupied = Barrier::new(threads);
670 let finished = Barrier::new(threads);
671 let releasing = std::sync::Mutex::new(releasing);
672 first_pool.broadcast(|context| {
673 occupied.wait();
674 if context.index() == 0 {
675 entered.send(()).unwrap();
677 releasing
678 .lock()
679 .unwrap()
680 .recv_timeout(Duration::from_secs(10))
681 .unwrap();
682 }
683 finished.wait();
684 context.index()
685 })
686 })
687 });
688 entering.recv_timeout(Duration::from_secs(10)).unwrap();
689 let second = catch_unwind(AssertUnwindSafe(|| {
690 Runtime::new().run(move || pool.broadcast(|context| context.index()))
691 }));
692 release.send(()).unwrap();
694 let first = first.join();
695 let expected = (0..threads).collect::<Vec<_>>();
696 assert_eq!(second.unwrap(), expected);
697 assert_eq!(first.unwrap(), expected);
698 }
699
700 fn wait_for_slot_waiter(pool: &ThreadPool) {
701 for _ in 0..10 {
703 if with_pool_slots(pool.id(), 1, |slots| !slots.waiters.is_empty()) {
704 break;
705 }
706 thread::yield_now();
707 }
708 with_pool_slots(pool.id(), 1, |slots| {
709 assert_eq!(slots.occupied, [true]);
710 assert_eq!(slots.waiters.len(), 1);
711 });
712 }
713 }
714}