Skip to main content

task/
join_handle.rs

1use synchronization::{Arc, blocking_mutex::raw::CriticalSectionRawMutex, signal::Signal};
2
3/// A result can cross threads only when it is Send.
4/// ```compile_fail
5/// fn require_send<T: Send>() {}
6/// require_send::<task::JoinHandle<std::rc::Rc<()>>>();
7/// ```
8/// ```compile_fail
9/// fn require_sync<T: Sync>() {}
10/// require_sync::<task::JoinHandle<std::rc::Rc<()>>>();
11/// ```
12pub struct JoinHandle<T>(Arc<Signal<CriticalSectionRawMutex, T>>);
13
14unsafe impl<T: Send> Send for JoinHandle<T> {}
15unsafe impl<T: Send> Sync for JoinHandle<T> {}
16
17impl<T> JoinHandle<T> {
18    pub fn new() -> (Self, Self) {
19        let signal = Signal::<CriticalSectionRawMutex, T>::new();
20
21        let arc = Arc::new(signal);
22
23        (Self(arc.clone()), Self(arc))
24    }
25
26    pub(crate) fn signal(&self, value: T) {
27        self.0.signal(value);
28    }
29
30    pub async fn join(self) -> T {
31        self.0.wait().await
32    }
33
34    /// Observe completion without consuming the result or waiting.
35    pub fn is_finished(&self) -> bool {
36        self.0.signaled()
37    }
38}