Skip to main content

dope_core/platform/thread/
mod.rs

1use std::{cell, marker, mem, num::NonZero, ptr, vec};
2
3use dope_sys::thread;
4use o3::alloc::{self, VecExt};
5
6use crate::Errno;
7
8mod raw;
9mod sealed;
10
11/// A single owned input transferred into a worker and returned as an output.
12pub trait Task: Send {
13    type Output: Send;
14    fn run(self) -> Self::Output;
15}
16
17impl<F: FnOnce() -> O + Send, O: Send> Task for F {
18    type Output = O;
19
20    fn run(self) -> O {
21        self()
22    }
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Error {
27    Attributes(Errno),
28    Create(Errno),
29}
30
31/// Builds the one allocation retained for the complete worker scope.
32pub struct Builder<T, O, P> {
33    slots: Vec<Slot<T, O, P>>,
34}
35
36impl<T, O, P> Builder<T, O, P> {
37    pub fn try_new(capacity: usize) -> Result<Self, alloc::Error> {
38        Ok(Self {
39            slots: Vec::try_new(capacity)?,
40        })
41    }
42
43    pub fn try_push(&mut self, task: T, parent: P) -> Result<(), alloc::Error> {
44        alloc::VecExt::try_vacant(&mut self.slots)?.insert(Slot {
45            value: cell::UnsafeCell::new(raw::Value::new(task)),
46            thread: cell::Cell::new(mem::MaybeUninit::uninit()),
47            parent,
48        });
49        Ok(())
50    }
51
52    /// Retains every started worker even if the borrowing view is forgotten.
53    pub fn scope<R>(mut self, run: impl for<'scope> FnOnce(Workers<'scope, T, O, P>) -> R) -> R {
54        let mut group = Group {
55            slots: mem::take(&mut self.slots),
56            started: 0,
57        };
58        let result = run(Workers {
59            group: &mut group,
60            owner: marker::PhantomData,
61        });
62        sealed::finish(&mut group);
63        result
64    }
65}
66
67impl<T, O, P> Drop for Builder<T, O, P> {
68    fn drop(&mut self) {
69        raw::cancel(self);
70    }
71}
72
73/// A worker's parent-only metadata and private transfer storage.
74pub struct Slot<T, O, P> {
75    value: cell::UnsafeCell<raw::Value<T, O>>,
76    thread: cell::Cell<mem::MaybeUninit<thread::raw::Handle>>,
77    parent: P,
78}
79
80impl<T, O, P> Slot<T, O, P> {
81    pub fn parent(&self) -> &P {
82        &self.parent
83    }
84}
85
86struct Group<T, O, P> {
87    slots: Vec<Slot<T, O, P>>,
88    started: usize,
89}
90
91/// Borrowing authority to start and observe the scope-owned workers.
92pub struct Workers<'scope, T, O, P> {
93    group: &'scope mut Group<T, O, P>,
94    owner: marker::PhantomData<fn(&'scope ()) -> &'scope ()>,
95}
96
97impl<T, O, P> Workers<'_, T, O, P> {
98    pub fn entries(&self) -> &[Slot<T, O, P>] {
99        &self.group.slots
100    }
101
102    /// Mutably borrows only coordinator metadata for the started worker prefix.
103    pub fn parents_mut(&mut self) -> impl ExactSizeIterator<Item = &mut P> {
104        raw::parents(self.group)
105    }
106
107    /// Spawns the remaining workers or borrows the first failed worker's parent.
108    pub fn start(&mut self, stack: NonZero<usize>) -> Result<(), (&P, Error)>
109    where
110        T: Task<Output = O>,
111    {
112        raw::start(self.group, stack)
113    }
114
115    pub fn finish(self) -> Finished<T, O, P> {
116        sealed::finish(self.group)
117    }
118}
119
120/// Joined outputs, in the original registration order.
121pub struct Finished<T, O, P> {
122    slots: vec::IntoIter<Slot<T, O, P>>,
123}
124
125impl<T, O, P> Iterator for Finished<T, O, P> {
126    type Item = (P, O);
127
128    fn next(&mut self) -> Option<Self::Item> {
129        raw::next(self)
130    }
131
132    fn size_hint(&self) -> (usize, Option<usize>) {
133        self.slots.size_hint()
134    }
135}
136
137impl<T, O, P> ExactSizeIterator for Finished<T, O, P> {}
138
139impl<T, O, P> Drop for Finished<T, O, P> {
140    fn drop(&mut self) {
141        raw::discard_outputs(self);
142    }
143}
144
145/// A single started worker borrowed from its enclosing native owner.
146pub struct Join<'scope, O> {
147    worker: &'scope mut Option<(thread::raw::Handle, ptr::NonNull<O>)>,
148}
149
150impl<O> Join<'_, O> {
151    /// Runs with one worker retained until native joining, even if Join is forgotten.
152    pub fn scope<T: Task<Output = O>, R>(
153        task: T,
154        stack: NonZero<usize>,
155        run: impl for<'scope> FnOnce(Join<'scope, O>) -> R,
156    ) -> Result<R, Error> {
157        let attrs = thread::raw::Attrs::with_stack(stack).map_err(Error::Attributes)?;
158        raw::single(task, attrs, run)
159    }
160
161    pub fn finish(self) -> O {
162        raw::output(self)
163    }
164}