1use std::any::Any;
2use std::cell::UnsafeCell;
3use std::mem;
4use std::sync::Arc;
56use crossbeam_deque::{Injector, Steal};
78use crate::latch::Latch;
9use crate::tlv::Tlv;
10use crate::{tlv, unwind};
1112pub(super) enum JobResult<T> {
13None,
14Ok(T),
15 Panic(Box<dyn Any + Send>),
16}
1718/// A `Job` is used to advertise work for other threads that they may
19/// want to steal. In accordance with time honored tradition, jobs are
20/// arranged in a deque, so that thieves can take from the top of the
21/// deque while the main worker manages the bottom of the deque. This
22/// deque is managed by the `thread_pool` module.
23pub(super) trait Job {
24/// Unsafe: this may be called from a different thread than the one
25 /// which scheduled the job, so the implementer must ensure the
26 /// appropriate traits are met, whether `Send`, `Sync`, or both.
27unsafe fn execute(this: *const ());
28}
2930#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for JobRefId {
}
#[automatically_derived]impl ::core::clone::Clone for JobRefId {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for JobRefId { }Copy, #[automatically_derived]impl ::core::fmt::Debug for JobRefId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"JobRefId pointer", &&self.pointer)
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for JobRefId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for JobRefId {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.pointer, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for JobRefId
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for JobRefId {
#[inline]
fn eq(&self, other: &Self) -> bool { self.pointer == other.pointer }
}PartialEq)]
31pub(super) struct JobRefId {
32 pointer: usize,
33}
3435/// Effectively a Job trait object. Each JobRef **must** be executed
36/// exactly once, or else data may leak.
37///
38/// Internally, we store the job's data in a `*const ()` pointer. The
39/// true type is something like `*const StackJob<...>`, but we hide
40/// it. We also carry the "execute fn" from the `Job` trait.
41pub(super) struct JobRef {
42 pointer: *const (),
43 execute_fn: unsafe fn(*const ()),
44}
4546unsafe impl Sendfor JobRef {}
47unsafe impl Syncfor JobRef {}
4849impl JobRef {
50/// Unsafe: caller asserts that `data` will remain valid until the
51 /// job is executed.
52pub(super) unsafe fn new<T>(data: *const T) -> JobRef53where
54T: Job,
55 {
56// erase types:
57JobRef { pointer: dataas *const (), execute_fn: <T as Job>::execute }
58 }
5960#[inline]
61pub(super) fn id(&self) -> JobRefId {
62JobRefId { pointer: self.pointer.expose_provenance() }
63 }
6465#[inline]
66pub(super) unsafe fn execute(self) {
67unsafe { (self.execute_fn)(self.pointer) }
68 }
69}
7071/// A job that will be owned by a stack slot. This means that when it
72/// executes it need not free any heap data, the cleanup occurs when
73/// the stack frame is later popped. The function parameter indicates
74/// `true` if the job was stolen -- executed on a different thread.
75pub(super) struct StackJob<L, F, R>
76where
77L: Latch + Sync,
78 F: FnOnce(bool) -> R + Send,
79 R: Send,
80{
81pub(super) latch: L,
82 func: UnsafeCell<Option<F>>,
83 result: UnsafeCell<JobResult<R>>,
84 tlv: Tlv,
85}
8687impl<L, F, R> StackJob<L, F, R>
88where
89L: Latch + Sync,
90 F: FnOnce(bool) -> R + Send,
91 R: Send,
92{
93pub(super) fn new(tlv: Tlv, func: F, latch: L) -> StackJob<L, F, R> {
94StackJob {
95latch,
96 func: UnsafeCell::new(Some(func)),
97 result: UnsafeCell::new(JobResult::None),
98tlv,
99 }
100 }
101102pub(super) unsafe fn as_job_ref(&self) -> JobRef {
103unsafe { JobRef::new(self) }
104 }
105106pub(super) unsafe fn run_inline(&self, stolen: bool) {
107unsafe {
108let func = (*self.func.get()).take().unwrap();
109*(self.result.get()) = match unwind::halt_unwinding(|| func(stolen)) {
110Ok(x) => JobResult::Ok(x),
111Err(x) => JobResult::Panic(x),
112 };
113 Latch::set(&self.latch);
114 }
115 }
116117pub(super) unsafe fn into_result(self) -> R {
118self.result.into_inner().into_return_value()
119 }
120}
121122impl<L, F, R> Jobfor StackJob<L, F, R>
123where
124L: Latch + Sync,
125 F: FnOnce(bool) -> R + Send,
126 R: Send,
127{
128unsafe fn execute(this: *const ()) {
129let this = unsafe { &*(thisas *const Self) };
130 tlv::set(this.tlv);
131let abort = unwind::AbortIfPanic;
132let func = unsafe { (*this.func.get()).take().unwrap() };
133unsafe {
134 (*this.result.get()) = JobResult::call(func);
135 }
136unsafe {
137 Latch::set(&this.latch);
138 }
139 mem::forget(abort);
140 }
141}
142143/// Represents a job stored in the heap. Used to implement
144/// `scope`. Unlike `StackJob`, when executed, `HeapJob` simply
145/// invokes a closure, which then triggers the appropriate logic to
146/// signal that the job executed.
147///
148/// (Probably `StackJob` should be refactored in a similar fashion.)
149pub(super) struct HeapJob<BODY>
150where
151BODY: FnOnce(JobRefId) + Send,
152{
153 job: BODY,
154 tlv: Tlv,
155}
156157impl<BODY> HeapJob<BODY>
158where
159BODY: FnOnce(JobRefId) + Send,
160{
161pub(super) fn new(tlv: Tlv, job: BODY) -> Box<Self> {
162Box::new(HeapJob { job, tlv })
163 }
164165/// Creates a `JobRef` from this job -- note that this hides all
166 /// lifetimes, so it is up to you to ensure that this JobRef
167 /// doesn't outlive any data that it closes over.
168pub(super) unsafe fn into_job_ref(self: Box<Self>) -> JobRef {
169unsafe { JobRef::new(Box::into_raw(self)) }
170 }
171172/// Creates a static `JobRef` from this job.
173pub(super) fn into_static_job_ref(self: Box<Self>) -> JobRef174where
175BODY: 'static,
176 {
177unsafe { self.into_job_ref() }
178 }
179}
180181impl<BODY> Jobfor HeapJob<BODY>
182where
183BODY: FnOnce(JobRefId) + Send,
184{
185unsafe fn execute(this: *const ()) {
186let pointer = this.expose_provenance();
187let this = unsafe { Box::from_raw(thisas *mut Self) };
188 tlv::set(this.tlv);
189 (this.job)(JobRefId { pointer });
190 }
191}
192193/// Represents a job stored in an `Arc` -- like `HeapJob`, but may
194/// be turned into multiple `JobRef`s and called multiple times.
195pub(super) struct ArcJob<BODY>
196where
197BODY: Fn(JobRefId) + Send + Sync,
198{
199 job: BODY,
200}
201202impl<BODY> ArcJob<BODY>
203where
204BODY: Fn(JobRefId) + Send + Sync,
205{
206pub(super) fn new(job: BODY) -> Arc<Self> {
207Arc::new(ArcJob { job })
208 }
209210/// Creates a `JobRef` from this job -- note that this hides all
211 /// lifetimes, so it is up to you to ensure that this JobRef
212 /// doesn't outlive any data that it closes over.
213pub(super) unsafe fn as_job_ref(this: &Arc<Self>) -> JobRef {
214unsafe { JobRef::new(Arc::into_raw(Arc::clone(this))) }
215 }
216217/// Creates a static `JobRef` from this job.
218pub(super) fn as_static_job_ref(this: &Arc<Self>) -> JobRef219where
220BODY: 'static,
221 {
222unsafe { Self::as_job_ref(this) }
223 }
224}
225226impl<BODY> Jobfor ArcJob<BODY>
227where
228BODY: Fn(JobRefId) + Send + Sync,
229{
230unsafe fn execute(this: *const ()) {
231let pointer = this.expose_provenance();
232let this = unsafe { Arc::from_raw(thisas *mut Self) };
233 (this.job)(JobRefId { pointer });
234 }
235}
236237impl<T> JobResult<T> {
238fn call(func: impl FnOnce(bool) -> T) -> Self {
239match unwind::halt_unwinding(|| func(true)) {
240Ok(x) => JobResult::Ok(x),
241Err(x) => JobResult::Panic(x),
242 }
243 }
244245/// Convert the `JobResult` for a job that has finished (and hence
246 /// its JobResult is populated) into its return value.
247 ///
248 /// NB. This will panic if the job panicked.
249pub(super) fn into_return_value(self) -> T {
250match self {
251 JobResult::None => ::core::panicking::unreachable_default_msg()unreachable!(),
252 JobResult::Ok(x) => x,
253 JobResult::Panic(x) => unwind::resume_unwinding(x),
254 }
255 }
256}
257258/// Indirect queue to provide FIFO job priority.
259pub(super) struct JobFifo {
260 inner: Injector<JobRef>,
261}
262263impl JobFifo {
264pub(super) fn new() -> Self {
265JobFifo { inner: Injector::new() }
266 }
267268pub(super) unsafe fn push(&self, job_ref: JobRef) -> JobRef {
269// A little indirection ensures that spawns are always prioritized in FIFO order. The
270 // jobs in a thread's deque may be popped from the back (LIFO) or stolen from the front
271 // (FIFO), but either way they will end up popping from the front of this queue.
272self.inner.push(job_ref);
273unsafe { JobRef::new(self) }
274 }
275}
276277impl Jobfor JobFifo {
278unsafe fn execute(this: *const ()) {
279// We "execute" a queue by executing its first job, FIFO.
280let this = unsafe { &*(thisas *const Self) };
281loop {
282match this.inner.steal() {
283 Steal::Success(job_ref) => break unsafe { job_ref.execute() },
284 Steal::Empty => { ::core::panicking::panic_fmt(format_args!("FIFO is empty")); }panic!("FIFO is empty"),
285 Steal::Retry => {}
286 }
287 }
288 }
289}