Skip to main content

reth_concurrency/sync/
thread.rs

1//! Standard-compatible threads and borrowed scopes for the selected backend.
2//!
3//! In simulation, `panicking()` reads the shared OS thread's unwind flag, not a logical task's
4//! state. It can therefore report another task's panic while an unwinding destructor yields.
5
6use 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/// A logical thread builder; scoped tasks inherit their scope's stack settings.
32#[cfg(all(feature = "fuzz", dst))]
33#[derive(Debug, Default)]
34pub struct Builder(thread::Builder);
35
36#[cfg(all(feature = "fuzz", dst))]
37impl Builder {
38    /// Creates a thread builder with default settings.
39    pub fn new() -> Self {
40        Self(thread::Builder::new())
41    }
42    /// Sets the name of a non-scoped logical thread.
43    pub fn name(self, name: String) -> Self {
44        Self(self.0.name(name))
45    }
46    /// Sets stack size for a non-scoped logical thread.
47    ///
48    /// Shuttle stack-allocation failures can panic during `spawn` instead of returning an I/O
49    /// error. Invalid sizes and allocation-failure handling are not simulated like native threads.
50    pub fn stack_size(self, size: usize) -> Self {
51        Self(self.0.stack_size(size))
52    }
53    /// Spawns a named logical thread in the current simulation.
54    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        // Publish completion inside the logical task, not from a destructor during teardown.
61        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    /// Spawns a borrowing logical thread; Shuttle does not support scoped metadata.
70    ///
71    /// Configured name and stack size apply only to non-scoped threads.
72    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/// Permission to join a logical thread and inspect whether its workload has finished.
86#[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    /// Waits for termination, including thread-local cleanup, and returns the workload's result.
96    pub fn join(self) -> Result<T> {
97        self.handle.join()?
98    }
99
100    /// Returns the logical thread associated with this handle.
101    pub fn thread(&self) -> &Thread {
102        self.handle.thread()
103    }
104
105    /// Returns whether the workload has returned or unwound; final thread cleanup may still run.
106    pub fn is_finished(&self) -> bool {
107        self.finished.load(Ordering::Acquire)
108    }
109}
110
111/// A borrowing scope that drains its children before propagating a panic.
112#[cfg(all(feature = "fuzz", dst))]
113#[derive(Debug)]
114pub struct Scope<'scope, 'env> {
115    // Published before children can access it and unchanged until every child has drained.
116    #[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    // Both lifetimes are invariant, as on the underlying borrowing scope.
127    lifetimes: PhantomData<&'scope mut &'scope &'env mut &'env ()>,
128}
129
130#[cfg(all(feature = "fuzz", dst))]
131impl<'scope, 'env> Scope<'scope, 'env> {
132    /// Spawns a borrowing thread; an unjoined panic propagates after the scope drains.
133    #[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        // SAFETY: `scope` initializes this pointer before exposing `self`. It keeps this wrapper
148        // alive until Shuttle drains every child, even if the callback panics. The invariant
149        // lifetimes prevent either the wrapper or a borrowing child from escaping that scope.
150        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/// Permission to join a borrowing logical thread and recover its workload's panic.
163#[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    /// Waits for termination and returns `Err` if the workload panicked.
175    ///
176    /// Joining handles the panic, so it will not propagate again at the end of the scope.
177    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    /// Returns the logical thread associated with this handle.
184    pub fn thread(&self) -> &Thread {
185        self.handle.thread()
186    }
187
188    /// Returns whether the workload has returned or unwound; final thread cleanup may still run.
189    pub fn is_finished(&self) -> bool {
190        self.finished.load(Ordering::Acquire)
191    }
192}
193
194// SAFETY: Shuttle's handle synchronizes result access internally. Its `PhantomData<&T>` is not
195// an actual shared borrow, so the panic payload need not be Sync to move or share the handle.
196#[cfg(all(feature = "fuzz", dst))]
197unsafe impl<T: Send> Send for ScopedJoinHandle<'_, T> {}
198
199// SAFETY: Shared access only exposes thread metadata and atomic flags; joining consumes the handle.
200#[cfg(all(feature = "fuzz", dst))]
201unsafe impl<T: Send> Sync for ScopedJoinHandle<'_, T> {}
202
203/// Returns available native parallelism, or one logical execution thread in simulation.
204#[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/// Spawns a logical thread in the current deterministic execution.
220#[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/// Runs a borrowing scope, waiting for all children even when the callback panics.
230///
231/// Unjoined child panics propagate after draining. A callback panic takes precedence.
232#[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        // Shuttle only drains children when its callback returns normally.
250        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}