Skip to main content

reth_concurrency/sync/
mod.rs

1//! Blocking execution primitives selected at compile time.
2//!
3//! The default backend uses native threads, Crossbeam channels, and Rayon. With
4//! both `fuzz` and `--cfg dst`, run callers inside `Runtime::run`: stackful Shuttle tasks execute
5//! on one OS thread in fixed round-robin order. Only primitives from this crate may
6//! block simulated tasks; native blocking or OS I/O is outside the simulation.
7
8#[cfg(not(all(feature = "fuzz", dst)))]
9pub use reth_primitives_traits::sync::{LazyLock, OnceLock};
10
11#[cfg(all(feature = "std", not(all(feature = "fuzz", dst))))]
12pub use std::{sync::*, thread_local};
13
14#[cfg(all(feature = "fuzz", dst))]
15pub use shuttle::thread_local;
16#[cfg(all(feature = "fuzz", dst))]
17pub use shuttle_sync::sync::{
18    atomic, Arc, Barrier, BarrierWaitResult, LockResult, Once, OnceState, PoisonError, RwLock,
19    RwLockReadGuard, RwLockWriteGuard, TryLockError, TryLockResult, Weak,
20};
21
22#[cfg(feature = "std")]
23pub mod channel;
24#[cfg(feature = "std")]
25pub mod iter;
26#[cfg(feature = "std")]
27pub mod pool;
28#[cfg(feature = "std")]
29pub mod runtime;
30
31#[cfg(feature = "std")]
32pub mod thread;
33#[cfg(feature = "std")]
34pub mod time;
35
36#[cfg(all(feature = "fuzz", dst))]
37mod deterministic;
38
39#[cfg(all(feature = "fuzz", dst))]
40mod condvar;
41#[cfg(all(feature = "fuzz", dst))]
42pub use condvar::{Condvar, WaitTimeoutResult};
43
44#[cfg(all(feature = "fuzz", dst))]
45mod mutex;
46#[cfg(all(feature = "fuzz", dst))]
47pub use mutex::{Mutex, MutexGuard};
48
49#[cfg(all(feature = "fuzz", dst))]
50pub use channel::mpsc;
51
52#[cfg(all(feature = "fuzz", dst))]
53mod once;
54#[cfg(all(feature = "fuzz", dst))]
55pub use once::{LazyLock, OnceLock};
56
57#[cfg(feature = "std")]
58pub use pool::{ThreadPool, ThreadPoolBuilder};
59
60#[cfg(feature = "std")]
61pub use runtime::Runtime;
62
63/// Rayon-compatible compute operations selected with the executor backend.
64#[cfg(feature = "std")]
65pub mod rayon {
66    pub use crate::sync::pool::*;
67    /// Parallel iterator extension traits for the selected compute backend.
68    pub mod prelude {
69        #[cfg(all(feature = "fuzz", dst))]
70        pub use crate::sync::iter::*;
71        #[cfg(not(all(feature = "fuzz", dst)))]
72        pub use ::rayon::prelude::*;
73    }
74    /// Slice sorting operations for the selected compute backend.
75    pub mod slice {
76        #[cfg(all(feature = "fuzz", dst))]
77        pub use crate::sync::iter::ParallelSliceMut;
78        #[cfg(not(all(feature = "fuzz", dst)))]
79        pub use ::rayon::slice::*;
80    }
81    /// Parallel iterator types for the selected compute backend.
82    pub mod iter {
83        pub use crate::sync::iter::*;
84    }
85}
86
87/// Native non-poisoning locks, or their Shuttle equivalents under `fuzz` plus `--cfg dst`.
88///
89/// Shuttle's `RwLock` currently queues readers behind pending writers even when an
90/// upgradable reader prevents that writer from acquiring the lock. Native `parking_lot`
91/// admits readers in that situation, so simulations of this pattern are unsupported.
92#[cfg(feature = "std")]
93pub mod parking_lot {
94    #[cfg(not(all(feature = "fuzz", dst)))]
95    pub use ::parking_lot::*;
96    #[cfg(all(feature = "fuzz", dst))]
97    pub use shuttle_parking_lot::*;
98
99    #[cfg(all(feature = "fuzz", dst))]
100    pub use super::Once;
101}
102
103/// Whether these primitives require an active simulated runtime.
104///
105/// Crates with backend-specific integration must select the same `fuzz` feature and `dst` cfg.
106pub const IS_SIMULATED: bool = cfg!(all(feature = "fuzz", dst));
107
108#[cfg(all(test, feature = "std"))]
109mod tests {
110    use super::*;
111    use crate::sync::{thread, time, Runtime};
112    use std::{
113        any::Any,
114        panic::{catch_unwind, AssertUnwindSafe},
115    };
116
117    #[test]
118    fn lazy_lock_initializes_once_for_racing_threads() {
119        Runtime::new().run(|| {
120            let calls = atomic::AtomicUsize::new(0);
121            let lazy = LazyLock::new(|| {
122                calls.fetch_add(1, atomic::Ordering::SeqCst);
123                // A simulated initializer must be able to block while contenders wait.
124                time::sleep(time::Duration::from_millis(1));
125                42
126            });
127            thread::scope(|scope| {
128                let handles = (0..4)
129                    .map(|_| scope.spawn(|| assert_eq!(*LazyLock::force(&lazy), 42)))
130                    .collect::<Vec<_>>();
131                for handle in handles {
132                    handle.join().unwrap();
133                }
134            });
135            assert_eq!(*lazy, 42);
136            assert_eq!(calls.load(atomic::Ordering::SeqCst), 1);
137        });
138    }
139
140    #[test]
141    fn lazy_lock_poison_wakes_contenders_without_retrying_initializer() {
142        Runtime::new().run(|| {
143            let calls = atomic::AtomicUsize::new(0);
144            let lazy = LazyLock::new(|| -> usize {
145                calls.fetch_add(1, atomic::Ordering::SeqCst);
146                time::sleep(time::Duration::from_millis(1));
147                panic!("lazy initializer failed");
148            });
149            let mut messages = thread::scope(|scope| {
150                let handles = (0..2)
151                    .map(|_| {
152                        scope.spawn(|| {
153                            panic_message(
154                                catch_unwind(AssertUnwindSafe(|| LazyLock::force(&lazy)))
155                                    .unwrap_err(),
156                            )
157                        })
158                    })
159                    .collect::<Vec<_>>();
160                handles.into_iter().map(|handle| handle.join().unwrap()).collect::<Vec<_>>()
161            });
162            messages.sort();
163            assert_eq!(
164                messages,
165                ["LazyLock instance has previously been poisoned", "lazy initializer failed"]
166            );
167            assert_eq!(calls.load(atomic::Ordering::SeqCst), 1);
168        });
169    }
170
171    #[test]
172    fn static_lazy_lock_retains_value_across_executions() {
173        static VALUE: LazyLock<Arc<usize>> = LazyLock::new(|| {
174            thread::yield_now();
175            Arc::new(42)
176        });
177        let values = (0..2)
178            .map(|_| {
179                Runtime::new().run(|| {
180                    thread::scope(|scope| {
181                        let first = scope.spawn(|| LazyLock::force(&VALUE));
182                        let second = scope.spawn(|| LazyLock::force(&VALUE));
183                        let first = first.join().unwrap();
184                        let second = second.join().unwrap();
185                        assert!(std::ptr::eq(first, second));
186                        assert_eq!(**second, 42);
187                        first.clone()
188                    })
189                })
190            })
191            .collect::<Vec<_>>();
192        // Keeping the first allocation alive also detects a newly initialized replacement.
193        assert!(Arc::ptr_eq(&values[0], &values[1]));
194    }
195
196    #[test]
197    fn static_lazy_lock_retains_poison_across_executions() {
198        static VALUE: LazyLock<usize> = LazyLock::new(|| panic!("static initializer failed"));
199        for expected in
200            ["static initializer failed", "LazyLock instance has previously been poisoned"]
201        {
202            Runtime::new().run(move || {
203                assert_eq!(
204                    panic_message(
205                        catch_unwind(AssertUnwindSafe(|| LazyLock::force(&VALUE))).unwrap_err()
206                    ),
207                    expected
208                );
209            });
210        }
211    }
212
213    #[test]
214    fn lazy_lock_default_and_value_drop() {
215        Runtime::new().run(|| {
216            let default: LazyLock<usize> = LazyLock::default();
217            assert_eq!(*default, 0);
218            let dropped = Arc::new(atomic::AtomicUsize::new(0));
219            let lazy = LazyLock::new({
220                let dropped = dropped.clone();
221                move || DropCounter(dropped)
222            });
223            LazyLock::force(&lazy);
224            assert_eq!(dropped.load(atomic::Ordering::SeqCst), 0);
225            drop(lazy);
226            assert_eq!(dropped.load(atomic::Ordering::SeqCst), 1);
227        });
228    }
229
230    #[cfg(not(all(feature = "fuzz", dst)))]
231    #[test]
232    fn native_lazy_lock_is_the_standard_type() {
233        let standard = std::sync::LazyLock::new(|| 42);
234        let selected: LazyLock<usize, _> = standard;
235        let round_trip: std::sync::LazyLock<usize, _> = selected;
236        assert_eq!(*std::sync::LazyLock::force(&round_trip), 42);
237    }
238
239    struct DropCounter(Arc<atomic::AtomicUsize>);
240
241    impl Drop for DropCounter {
242        fn drop(&mut self) {
243            self.0.fetch_add(1, atomic::Ordering::SeqCst);
244        }
245    }
246
247    fn panic_message(panic: Box<dyn Any + Send>) -> String {
248        if let Some(message) = panic.downcast_ref::<&str>() {
249            (*message).to_owned()
250        } else {
251            *panic.downcast::<String>().unwrap()
252        }
253    }
254}