|
| 1 | +use core::cell::Cell; |
| 2 | +use thread_local::ThreadLocal; |
| 3 | + |
| 4 | +/// A cohesive set of thread-local values of a given type. |
| 5 | +/// |
| 6 | +/// Mutable references can be fetched if `T: Default` via [`Parallel::scope`]. |
| 7 | +#[derive(Default)] |
| 8 | +pub struct Parallel<T: Send> { |
| 9 | + locals: ThreadLocal<Cell<T>>, |
| 10 | +} |
| 11 | + |
| 12 | +impl<T: Send> Parallel<T> { |
| 13 | + /// Gets a mutable iterator over all of the per-thread queues. |
| 14 | + pub fn iter_mut(&mut self) -> impl Iterator<Item = &'_ mut T> { |
| 15 | + self.locals.iter_mut().map(|cell| cell.get_mut()) |
| 16 | + } |
| 17 | + |
| 18 | + /// Clears all of the stored thread local values. |
| 19 | + pub fn clear(&mut self) { |
| 20 | + self.locals.clear(); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl<T: Default + Send> Parallel<T> { |
| 25 | + /// Retrieves the thread-local value for the current thread and runs `f` on it. |
| 26 | + /// |
| 27 | + /// If there is no thread-local value, it will be initialized to it's default. |
| 28 | + pub fn scope<R>(&self, f: impl FnOnce(&mut T) -> R) -> R { |
| 29 | + let cell = self.locals.get_or_default(); |
| 30 | + let mut value = cell.take(); |
| 31 | + let ret = f(&mut value); |
| 32 | + cell.set(value); |
| 33 | + ret |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl<T, I> Parallel<I> |
| 38 | +where |
| 39 | + I: IntoIterator<Item = T> + Default + Send + 'static, |
| 40 | +{ |
| 41 | + /// Drains all enqueued items from all threads and returns an iterator over them. |
| 42 | + /// |
| 43 | + /// Unlike [`Vec::drain`], this will piecemeal remove chunks of the data stored. |
| 44 | + /// If iteration is terminated part way, the rest of the enqueued items in the same |
| 45 | + /// chunk will be dropped, and the rest of the undrained elements will remain. |
| 46 | + /// |
| 47 | + /// The ordering is not guaranteed. |
| 48 | + pub fn drain<B>(&mut self) -> impl Iterator<Item = T> + '_ |
| 49 | + where |
| 50 | + B: FromIterator<T>, |
| 51 | + { |
| 52 | + self.locals.iter_mut().flat_map(|item| item.take()) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<T: Send> Parallel<Vec<T>> { |
| 57 | + /// Collect all enqueued items from all threads and appends them to the end of a |
| 58 | + /// single Vec. |
| 59 | + /// |
| 60 | + /// The ordering is not guarenteed. |
| 61 | + pub fn drain_into(&mut self, out: &mut Vec<T>) { |
| 62 | + let size = self |
| 63 | + .locals |
| 64 | + .iter_mut() |
| 65 | + .map(|queue| queue.get_mut().len()) |
| 66 | + .sum(); |
| 67 | + out.reserve(size); |
| 68 | + for queue in self.locals.iter_mut() { |
| 69 | + out.append(queue.get_mut()); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments