solar_data_structures/
sync.rs

1pub use parking_lot::{
2    MappedMutexGuard as MappedLockGuard, MappedRwLockReadGuard as MappedReadGuard,
3    MappedRwLockWriteGuard as MappedWriteGuard, Mutex as Lock, RwLock,
4    RwLockReadGuard as ReadGuard, RwLockWriteGuard as WriteGuard,
5};
6
7/// Executes the given expressions in parallel.
8#[macro_export]
9macro_rules! parallel {
10    ($sess:expr, $first:expr $(, $blocks:expr)+ $(,)?) => {
11        $sess.scope(|scope| {
12            $(
13                scope.spawn(|_| $blocks);
14            )+
15            $first;
16        })
17    };
18}
19
20/// A dynamic fork-join scope.
21///
22/// See [`rayon::scope`] for more details.
23pub struct Scope<'r, 'scope>(Option<&'r rayon::Scope<'scope>>);
24
25impl<'r, 'scope> Scope<'r, 'scope> {
26    /// Creates a new scope.
27    #[inline]
28    fn new(scope: Option<&'r rayon::Scope<'scope>>) -> Self {
29        Self(scope)
30    }
31
32    /// Spawns a job into the fork-join scope `self`.
33    #[inline]
34    pub fn spawn<BODY>(&self, body: BODY)
35    where
36        BODY: FnOnce(Scope<'_, 'scope>) + Send + 'scope,
37    {
38        match self.0 {
39            Some(scope) => scope.spawn(|scope| body(Scope::new(Some(scope)))),
40            None => body(Scope::new(None)),
41        }
42    }
43}
44
45/// Creates a new fork-join scope.
46///
47/// See [`rayon::scope`] for more details.
48#[inline]
49pub fn scope<'scope, OP, R>(enabled: bool, op: OP) -> R
50where
51    OP: FnOnce(Scope<'_, 'scope>) -> R + Send,
52    R: Send,
53{
54    if enabled { rayon::scope(|scope| op(Scope::new(Some(scope)))) } else { op(Scope::new(None)) }
55}