rustc_thread_pool/
worker_local.rs1use std::fmt;
2use std::ops::Deref;
3use std::sync::Arc;
4
5use crate::registry::{Registry, WorkerThread};
6
7#[repr(align(64))]
8#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for CacheAligned<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CacheAligned",
&&self.0)
}
}Debug)]
9struct CacheAligned<T>(T);
10
11pub struct WorkerLocal<T> {
15 locals: Vec<CacheAligned<T>>,
16 registry: Arc<Registry>,
17}
18
19unsafe impl<T: Send> Sync for WorkerLocal<T> {}
23
24impl<T> WorkerLocal<T> {
25 #[inline]
28 pub fn new<F: FnMut(usize) -> T>(mut initial: F) -> WorkerLocal<T> {
29 let registry = Registry::current();
30 WorkerLocal {
31 locals: (0..registry.num_threads()).map(|i| CacheAligned(initial(i))).collect(),
32 registry,
33 }
34 }
35
36 #[inline]
38 pub fn into_inner(self) -> Vec<T> {
39 self.locals.into_iter().map(|c| c.0).collect()
40 }
41
42 fn current(&self) -> &T {
43 unsafe {
44 let worker_thread = WorkerThread::current();
45 if 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}
54
55impl<T> WorkerLocal<Vec<T>> {
56 pub fn join(self) -> Vec<T> {
58 self.into_inner().into_iter().flatten().collect()
59 }
60}
61
62impl<T: fmt::Debug> fmt::Debug for WorkerLocal<T> {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.debug_struct("WorkerLocal").field("registry", &self.registry.id()).finish()
65 }
66}
67
68impl<T> Deref for WorkerLocal<T> {
69 type Target = T;
70
71 #[inline(always)]
72 fn deref(&self) -> &T {
73 self.current()
74 }
75}