1use std::{io, num::NonZeroUsize};
7
8#[cfg(all(feature = "fuzz", dst))]
9use shuttle::{sync::atomic::AtomicBool, thread};
10#[cfg(all(feature = "fuzz", dst))]
11use std::{
12 convert::identity,
13 marker::PhantomData,
14 panic::{catch_unwind, resume_unwind, AssertUnwindSafe},
15 ptr,
16 sync::{
17 atomic::{AtomicPtr, Ordering},
18 Arc, Mutex,
19 },
20};
21
22pub use crate::sync::time::sleep;
23#[cfg(all(feature = "fuzz", dst))]
24pub use shuttle::thread::{current, panicking, park, yield_now, Result, Thread, ThreadId};
25#[cfg(not(all(feature = "fuzz", dst)))]
26pub use std::thread::{
27 current, panicking, park, scope, spawn, yield_now, Builder, JoinHandle, Result, Scope,
28 ScopedJoinHandle, Thread, ThreadId,
29};
30
31#[cfg(all(feature = "fuzz", dst))]
33#[derive(Debug, Default)]
34pub struct Builder(thread::Builder);
35
36#[cfg(all(feature = "fuzz", dst))]
37impl Builder {
38 pub fn new() -> Self {
40 Self(thread::Builder::new())
41 }
42 pub fn name(self, name: String) -> Self {
44 Self(self.0.name(name))
45 }
46 pub fn stack_size(self, size: usize) -> Self {
51 Self(self.0.stack_size(size))
52 }
53 pub fn spawn<F, T>(self, work: F) -> io::Result<JoinHandle<T>>
55 where
56 F: FnOnce() -> T + Send + 'static,
57 T: Send + 'static,
58 {
59 let finished = Arc::new(AtomicBool::new(false));
60 let completed = finished.clone();
62 let handle = self.0.spawn(move || {
63 let result = catch_unwind(AssertUnwindSafe(work));
64 completed.store(true, Ordering::Release);
65 result
66 })?;
67 Ok(JoinHandle { handle, finished })
68 }
69 pub fn spawn_scoped<'scope, 'env, F, T>(
73 self,
74 scope: &'scope Scope<'scope, 'env>,
75 work: F,
76 ) -> io::Result<ScopedJoinHandle<'scope, T>>
77 where
78 F: FnOnce() -> T + Send + 'scope,
79 T: Send + 'scope,
80 {
81 Ok(scope.spawn(work))
82 }
83}
84
85#[cfg(all(feature = "fuzz", dst))]
87#[derive(Debug)]
88pub struct JoinHandle<T> {
89 handle: thread::JoinHandle<Result<T>>,
90 finished: Arc<AtomicBool>,
91}
92
93#[cfg(all(feature = "fuzz", dst))]
94impl<T> JoinHandle<T> {
95 pub fn join(self) -> Result<T> {
97 self.handle.join()?
98 }
99
100 pub fn thread(&self) -> &Thread {
102 self.handle.thread()
103 }
104
105 pub fn is_finished(&self) -> bool {
107 self.finished.load(Ordering::Acquire)
108 }
109}
110
111#[cfg(all(feature = "fuzz", dst))]
113#[derive(Debug)]
114pub struct Scope<'scope, 'env> {
115 #[allow(
117 clippy::disallowed_types,
118 reason = "Native pointer publishes the borrowed Shuttle scope."
119 )]
120 inner: AtomicPtr<()>,
121 #[allow(
122 clippy::disallowed_types,
123 reason = "Native storage is never locked across a scheduler operation."
124 )]
125 child_panics: Mutex<Vec<Arc<AtomicBool>>>,
126 lifetimes: PhantomData<&'scope mut &'scope &'env mut &'env ()>,
128}
129
130#[cfg(all(feature = "fuzz", dst))]
131impl<'scope, 'env> Scope<'scope, 'env> {
132 #[allow(
134 clippy::disallowed_methods,
135 reason = "The bookkeeping lock only appends a flag before spawning."
136 )]
137 pub fn spawn<F, T>(&'scope self, work: F) -> ScopedJoinHandle<'scope, T>
138 where
139 F: FnOnce() -> T + Send + 'scope,
140 T: Send + 'scope,
141 {
142 let finished = Arc::new(AtomicBool::new(false));
143 let completed = finished.clone();
144 let panicked = Arc::new(AtomicBool::new(false));
145 self.child_panics.lock().unwrap_or_else(|error| error.into_inner()).push(panicked.clone());
146 let child_panicked = panicked.clone();
147 let inner =
151 unsafe { &*self.inner.load(Ordering::Acquire).cast::<thread::Scope<'scope, 'env>>() };
152 let handle = inner.spawn(move || {
153 let result = catch_unwind(AssertUnwindSafe(work));
154 child_panicked.store(result.is_err(), Ordering::Release);
155 completed.store(true, Ordering::Release);
156 result
157 });
158 ScopedJoinHandle { handle, finished, panicked, lifetime: PhantomData }
159 }
160}
161
162#[cfg(all(feature = "fuzz", dst))]
164#[derive(Debug)]
165pub struct ScopedJoinHandle<'scope, T> {
166 handle: thread::ScopedJoinHandle<'scope, Result<T>>,
167 finished: Arc<AtomicBool>,
168 panicked: Arc<AtomicBool>,
169 lifetime: PhantomData<&'scope mut &'scope ()>,
170}
171
172#[cfg(all(feature = "fuzz", dst))]
173impl<T> ScopedJoinHandle<'_, T> {
174 pub fn join(self) -> Result<T> {
178 let result = self.handle.join().and_then(identity);
179 self.panicked.store(false, Ordering::Release);
180 result
181 }
182
183 pub fn thread(&self) -> &Thread {
185 self.handle.thread()
186 }
187
188 pub fn is_finished(&self) -> bool {
190 self.finished.load(Ordering::Acquire)
191 }
192}
193
194#[cfg(all(feature = "fuzz", dst))]
197unsafe impl<T: Send> Send for ScopedJoinHandle<'_, T> {}
198
199#[cfg(all(feature = "fuzz", dst))]
201unsafe impl<T: Send> Sync for ScopedJoinHandle<'_, T> {}
202
203#[cfg_attr(
205 all(feature = "fuzz", dst),
206 expect(clippy::missing_const_for_fn, reason = "The native implementation queries the OS.")
207)]
208pub fn available_parallelism() -> io::Result<NonZeroUsize> {
209 #[cfg(not(all(feature = "fuzz", dst)))]
210 {
211 std::thread::available_parallelism()
212 }
213 #[cfg(all(feature = "fuzz", dst))]
214 {
215 Ok(NonZeroUsize::MIN)
216 }
217}
218
219#[cfg(all(feature = "fuzz", dst))]
221pub fn spawn<F, T>(work: F) -> JoinHandle<T>
222where
223 F: FnOnce() -> T + Send + 'static,
224 T: Send + 'static,
225{
226 Builder::new().spawn(work).expect("Shuttle logical thread creation is infallible")
227}
228
229#[cfg(all(feature = "fuzz", dst))]
233#[allow(
234 clippy::disallowed_types,
235 clippy::disallowed_methods,
236 reason = "Native scope pointer and panic-list storage are initialized before spawning and read after children drain."
237)]
238pub fn scope<'env, F, T>(work: F) -> T
239where
240 F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T,
241{
242 let scope = Scope {
243 inner: AtomicPtr::new(ptr::null_mut()),
244 child_panics: Mutex::new(Vec::new()),
245 lifetimes: PhantomData,
246 };
247 let result = thread::scope(|inner| {
248 scope.inner.store(ptr::from_ref(inner).cast_mut().cast(), Ordering::Release);
249 catch_unwind(AssertUnwindSafe(|| work(&scope)))
251 });
252 match result {
253 Err(panic) => resume_unwind(panic),
254 Ok(value) => {
255 let child_panics = std::mem::take(
256 &mut *scope.child_panics.lock().unwrap_or_else(|error| error.into_inner()),
257 );
258 assert!(
259 !child_panics.iter().any(|panicked| panicked.load(Ordering::Acquire)),
260 "a scoped thread panicked"
261 );
262 value
263 }
264 }
265}