Skip to main content

aoc/util/
thread.rs

1//! Utility methods to spawn a number of
2//! [scoped](https://doc.rust-lang.org/stable/std/thread/fn.scope.html)
3//! threads equal to the number of cores on the machine. Unlike normal threads, scoped threads
4//! can borrow data from their environment.
5use 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        // First try taking from our own queue.
20        let worker = &self.workers[self.id];
21        let current = worker.increment();
22        let (start, end) = unpack(current);
23
24        // There are still items to process.
25        if start < end {
26            return Some(&self.items[start]);
27        }
28
29        // Steal from another worker, [spinlocking](https://en.wikipedia.org/wiki/Spinlock)
30        // until we acquire new items to process or there's nothing left to do.
31        loop {
32            // Find worker with the most remaining items, breaking out of the loop
33            // and returning `None` if there is no work remaining.
34            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            // Split the work items into two roughly equal piles.
47            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            // We could be preempted by another thread stealing or by the owning worker
54            // thread finishing an item, so check indices are still unmodified.
55            if other.compare_exchange(current, next) {
56                worker.store(stolen);
57                break Some(&self.items[middle]);
58            }
59        }
60    }
61}
62
63/// Intentionally force alignment to 128 bytes to make a best effort attempt to place each atomic
64/// on its own cache line. This reduces contention and improves performance for common
65/// CPU caching protocols such as [MESI](https://en.wikipedia.org/wiki/MESI_protocol).
66#[repr(align(128))]
67struct CachePadding {
68    atomic: AtomicUsize,
69}
70
71/// Convenience wrapper methods around atomic operations. Both start and end indices are packed
72/// into a single atomic so that we can use the fastest and easiest to reason about `Relaxed`
73/// ordering.
74impl 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
101/// Shares a monotonically increasing value between multiple threads.
102pub 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/// Usually the number of physical cores.
125#[must_use]
126pub fn threads() -> usize {
127    available_parallelism().unwrap().get()
128}
129
130/// Spawn `n` scoped threads, where `n` is the available parallelism.
131pub 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/// Spawns `n` scoped threads that each receive a
143/// [work stealing](https://en.wikipedia.org/wiki/Work_stealing) iterator.
144/// Work stealing is an efficient strategy that keeps each CPU core busy when some items take longer
145/// than others to process, used by popular libraries such as [rayon](https://github.com/rayon-rs/rayon).
146/// Processing at different rates also happens on many modern CPUs with
147/// [heterogeneous performance and efficiency cores](https://en.wikipedia.org/wiki/ARM_big.LITTLE).
148#[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    // Initially divide work as evenly as possible among the worker threads.
159    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}