1use std::sync::atomic::Ordering::Relaxed;
6use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize};
7use std::thread::*;
8
9pub struct ParIter<'a, T> {
10 id: usize,
11 items: &'a [T],
12 workers: &'a [CachePadding],
13}
14
15impl<'a, T> Iterator for ParIter<'a, T> {
16 type Item = &'a T;
17
18 fn next(&mut self) -> Option<Self::Item> {
19 let worker = &self.workers[self.id];
21 let current = worker.increment();
22 let (start, end) = unpack(current);
23
24 if start < end {
26 return Some(&self.items[start]);
27 }
28
29 loop {
32 let (other, current, _) = self
35 .workers
36 .iter()
37 .filter_map(|other| {
38 let current = other.load();
39 let (start, end) = unpack(current);
40 let size = end.saturating_sub(start);
41
42 (size > 1).then_some((other, current, size))
43 })
44 .max_by_key(|&(.., size)| size)?;
45
46 let (start, end) = unpack(current);
48 let middle = start.midpoint(end);
49
50 let next = pack(start, middle);
51 let stolen = pack(middle + 1, end);
52
53 if other.compare_exchange(current, next) {
56 worker.store(stolen);
57 break Some(&self.items[middle]);
58 }
59 }
60 }
61}
62
63#[repr(align(128))]
67struct CachePadding {
68 atomic: AtomicUsize,
69}
70
71impl CachePadding {
75 #[inline]
76 fn new(n: usize) -> Self {
77 Self { atomic: AtomicUsize::new(n) }
78 }
79
80 #[inline]
81 fn increment(&self) -> usize {
82 self.atomic.fetch_add(1, Relaxed)
83 }
84
85 #[inline]
86 fn load(&self) -> usize {
87 self.atomic.load(Relaxed)
88 }
89
90 #[inline]
91 fn store(&self, n: usize) {
92 self.atomic.store(n, Relaxed);
93 }
94
95 #[inline]
96 fn compare_exchange(&self, current: usize, new: usize) -> bool {
97 self.atomic.compare_exchange(current, new, Relaxed, Relaxed).is_ok()
98 }
99}
100
101pub struct AtomicIter {
103 running: AtomicBool,
104 index: AtomicU32,
105 step: u32,
106}
107
108impl AtomicIter {
109 #[must_use]
110 pub fn new(start: u32, step: u32) -> Self {
111 Self { running: AtomicBool::new(true), index: AtomicU32::new(start), step }
112 }
113
114 #[must_use]
115 pub fn next(&self) -> Option<u32> {
116 self.running.load(Relaxed).then(|| self.index.fetch_add(self.step, Relaxed))
117 }
118
119 pub fn stop(&self) {
120 self.running.store(false, Relaxed);
121 }
122}
123
124#[must_use]
126pub fn threads() -> usize {
127 available_parallelism().unwrap().get()
128}
129
130pub fn spawn<F, R>(f: F) -> Vec<R>
132where
133 F: Fn() -> R + Copy + Send,
134 R: Send,
135{
136 scope(|scope| {
137 let handles = Vec::from_fn(threads(), |_| scope.spawn(f));
138 handles.into_iter().flat_map(ScopedJoinHandle::join).collect()
139 })
140}
141
142#[must_use]
149pub fn spawn_parallel_iterator<F, R, T>(items: &[T], f: F) -> Vec<R>
150where
151 F: Fn(ParIter<'_, T>) -> R + Copy + Send,
152 R: Send,
153 T: Sync,
154{
155 let threads = threads();
156 let size = items.len().div_ceil(threads);
157
158 let workers = Vec::from_fn(threads, |id| {
160 let start = (id * size).min(items.len());
161 let end = (start + size).min(items.len());
162 CachePadding::new(pack(start, end))
163 });
164 let workers = workers.as_slice();
165
166 scope(|scope| {
167 let handles =
168 Vec::from_fn(threads, |id| scope.spawn(move || f(ParIter { id, items, workers })));
169 handles.into_iter().flat_map(ScopedJoinHandle::join).collect()
170 })
171}
172
173#[inline]
174fn pack(start: usize, end: usize) -> usize {
175 (end << 32) | start
176}
177
178#[inline]
179fn unpack(both: usize) -> (usize, usize) {
180 (both & 0xffffffff, both >> 32)
181}