1use std::fmt;
2use std::ops::Deref;
3use std::sync::Arc;
45use crate::registry::{Registry, WorkerThread};
67#[repr(align(64))]
8#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
CacheAligned<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "CacheAligned",
&&self.0)
}
}Debug)]
9struct CacheAligned<T>(T);
1011/// Holds worker-locals values for each thread in a thread pool.
12/// You can only access the worker local value through the Deref impl
13/// on the thread pool it was constructed on. It will panic otherwise
14pub struct WorkerLocal<T> {
15 locals: Vec<CacheAligned<T>>,
16 registry: Arc<Registry>,
17}
1819/// We prevent concurrent access to the underlying value in the
20/// Deref impl, thus any values safe to send across threads can
21/// be used with WorkerLocal.
22unsafe impl<T: Send> Syncfor WorkerLocal<T> {}
2324impl<T> WorkerLocal<T> {
25/// Creates a new worker local where the `initial` closure computes the
26 /// value this worker local should take for each thread in the thread pool.
27#[inline]
28pub fn new<F: FnMut(usize) -> T>(mut initial: F) -> WorkerLocal<T> {
29let registry = Registry::current();
30WorkerLocal {
31 locals: (0..registry.num_threads()).map(|i| CacheAligned(initial(i))).collect(),
32registry,
33 }
34 }
3536/// Returns the worker-local value for each thread
37#[inline]
38pub fn into_inner(self) -> Vec<T> {
39self.locals.into_iter().map(|c| c.0).collect()
40 }
4142fn current(&self) -> &T {
43unsafe {
44let worker_thread = WorkerThread::current();
45if worker_thread.is_null()
46 || !std::ptr::eq(&*(*worker_thread).registry, &*self.registry)
47 {
48{
::core::panicking::panic_fmt(format_args!("WorkerLocal can only be used on the thread pool it was created on"));
}panic!("WorkerLocal can only be used on the thread pool it was created on")49 }
50&self.locals[(*worker_thread).index].0
51}
52 }
53}
5455impl<T> WorkerLocal<Vec<T>> {
56/// Joins the elements of all the worker locals into one Vec
57pub fn join(self) -> Vec<T> {
58self.into_inner().into_iter().flatten().collect()
59 }
60}
6162impl<T: fmt::Debug> fmt::Debugfor WorkerLocal<T> {
63fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64f.debug_struct("WorkerLocal").field("registry", &self.registry.id()).finish()
65 }
66}
6768impl<T> Dereffor WorkerLocal<T> {
69type Target = T;
7071#[inline(always)]
72fn deref(&self) -> &T {
73self.current()
74 }
75}