solar_data_structures/
sync.rs1use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2
3pub use parking_lot::{
4 MappedMutexGuard, MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock,
5 RwLockReadGuard, RwLockWriteGuard,
6};
7
8#[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
21pub struct Scope<'r, 'scope>(Option<&'r rayon::Scope<'scope>>);
25
26impl<'r, 'scope> Scope<'r, 'scope> {
27 #[inline]
29 fn new(scope: Option<&'r rayon::Scope<'scope>>) -> Self {
30 Self(scope)
31 }
32
33 #[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#[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
58pub 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 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 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 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}