Skip to main content

solar_data_structures/
sync.rs

1use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2
3pub use parking_lot::{
4    MappedMutexGuard, MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock,
5    RwLockReadGuard, RwLockWriteGuard,
6};
7
8/// Executes the given expressions in parallel.
9#[macro_export]
10macro_rules! parallel {
11    ($sess:expr, $first:expr $(, $blocks:expr)+ $(,)?) => {
12        $sess.scope(|scope| {
13            $(
14                scope.spawn(|_| $blocks);
15            )+
16            $first;
17        })
18    };
19}
20
21/// A dynamic fork-join scope.
22///
23/// See [`rayon::scope`] for more details.
24pub struct Scope<'r, 'scope>(Option<&'r rayon::Scope<'scope>>);
25
26impl<'r, 'scope> Scope<'r, 'scope> {
27    /// Creates a new scope.
28    #[inline]
29    fn new(scope: Option<&'r rayon::Scope<'scope>>) -> Self {
30        Self(scope)
31    }
32
33    /// Spawns a job into the fork-join scope `self`.
34    #[inline]
35    pub fn spawn<BODY>(&self, body: BODY)
36    where
37        BODY: FnOnce(Scope<'_, 'scope>) + Send + 'scope,
38    {
39        match self.0 {
40            Some(scope) => scope.spawn(|scope| body(Scope::new(Some(scope)))),
41            None => body(Scope::new(None)),
42        }
43    }
44}
45
46/// Creates a new fork-join scope.
47///
48/// See [`rayon::scope`] for more details.
49#[inline]
50pub fn scope<'scope, OP, R>(enabled: bool, op: OP) -> R
51where
52    OP: FnOnce(Scope<'_, 'scope>) -> R + Send,
53    R: Send,
54{
55    if enabled { rayon::scope(|scope| op(Scope::new(Some(scope)))) } else { op(Scope::new(None)) }
56}
57
58/// Maps `f` over `items` and returns the results in item order, or the first error in item order.
59///
60/// When `enabled`, idle rayon workers help the calling thread: it claims items from a shared
61/// counter and runs them itself, and spawns helpers that claim items the same way. A helper that
62/// starts late finds nothing left and returns. Unlike a rayon join or parallel iterator, the
63/// caller waits for helpers that are still running an item by yielding, not inside rayon, so it
64/// does not pick up an unrelated queued job and run it before its own continuation. Only the
65/// scope's end waits inside rayon, and only for helpers that have no item left.
66///
67/// A serial map stops at the first error; a parallel one stops claiming items after one.
68pub fn par_try_map<T, R, E, F>(enabled: bool, items: Vec<T>, f: F) -> Result<Vec<R>, E>
69where
70    T: Send,
71    R: Send,
72    E: Send,
73    F: Fn(T) -> Result<R, E> + Sync,
74{
75    let len = items.len();
76    if !enabled || len < 2 {
77        let mut results = Vec::with_capacity(len);
78        for item in items {
79            results.push(f(item)?);
80        }
81        return Ok(results);
82    }
83
84    let inputs = items.into_iter().map(|item| Mutex::new(Some(item))).collect::<Vec<_>>();
85    let outputs = (0..len).map(|_| Mutex::new(None)).collect::<Vec<_>>();
86    let next = AtomicUsize::new(0);
87    let active = AtomicUsize::new(0);
88    let failed = AtomicBool::new(false);
89    // Leaves `active` and, on a panic, stops the other workers, so the caller's wait ends and
90    // the scope can rethrow the panic.
91    struct Active<'a> {
92        active: &'a AtomicUsize,
93        failed: &'a AtomicBool,
94    }
95    impl Drop for Active<'_> {
96        fn drop(&mut self) {
97            if std::thread::panicking() {
98                self.failed.store(true, Ordering::Relaxed);
99            }
100            self.active.fetch_sub(1, Ordering::AcqRel);
101        }
102    }
103    let work = || {
104        // The read-modify-writes on `active` order the relaxed accesses to `next` and `failed`: a
105        // helper that starts after the caller's wait ended sees the counter exhausted.
106        active.fetch_add(1, Ordering::AcqRel);
107        let _active = Active { active: &active, failed: &failed };
108        while !failed.load(Ordering::Relaxed) {
109            let index = next.fetch_add(1, Ordering::Relaxed);
110            let Some(input) = inputs.get(index) else { break };
111            let result = f(input.lock().take().expect("item claimed once"));
112            if result.is_err() {
113                failed.store(true, Ordering::Relaxed);
114            }
115            *outputs[index].lock() = Some(result);
116        }
117    };
118    rayon::scope(|scope| {
119        for _ in 1..len.min(rayon::current_num_threads()) {
120            scope.spawn(|_| work());
121        }
122        work();
123        // A helper that claimed an item has counted itself in `active` first.
124        while active.load(Ordering::Acquire) != 0 {
125            std::thread::yield_now();
126        }
127    });
128
129    outputs
130        .into_iter()
131        .map(|output| output.into_inner().expect("items before the first error ran"))
132        .collect()
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn par_try_map_keeps_item_order() {
141        let items = (0..200u32).collect::<Vec<_>>();
142        let mapped = par_try_map(true, items.clone(), |item| Ok::<_, ()>(item * 2));
143        assert_eq!(mapped, Ok(items.iter().map(|item| item * 2).collect()));
144    }
145
146    #[test]
147    fn par_try_map_returns_first_error_in_item_order() {
148        for enabled in [false, true] {
149            let items = (0..200u32).collect::<Vec<_>>();
150            let mapped = par_try_map(enabled, items, |item| {
151                if item % 50 == 7 {
152                    std::thread::sleep(std::time::Duration::from_millis(u64::from(200 - item)));
153                    Err(item)
154                } else {
155                    Ok(item)
156                }
157            });
158            assert_eq!(mapped, Err(7));
159        }
160    }
161}