Skip to main content

externally_driven_async_rt/tasks/
join_handle.rs

1use core::{future::Future, pin::Pin, task::Poll};
2
3use crate::tasks::{JoinStatus, TaskId, TasksGuard};
4
5/// A join handle of the spawned task, resolves once the task is finished.
6pub struct JoinHandle<'a, const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize> {
7    tasks: TasksGuard<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
8    id: TaskId,
9}
10
11impl<'a, const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize>
12    JoinHandle<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
13{
14    pub(crate) fn new(tasks: TasksGuard<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>, id: TaskId) -> Self {
15        Self { tasks, id }
16    }
17}
18
19impl<const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize> Future
20    for JoinHandle<'_, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
21{
22    type Output = ();
23
24    fn poll(self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<()> {
25        match self.tasks.set_join_waiter(self.id, cx.waker()) {
26            JoinStatus::Running => Poll::Pending,
27            JoinStatus::Finished => Poll::Ready(()),
28        }
29    }
30}
31
32impl<const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize> core::fmt::Debug
33    for JoinHandle<'_, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
34{
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        f.write_str("JoinHandle")
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use core::future::pending;
43
44    use crate::{
45        Error, Selector,
46        testing::{EventLoopTestingExt, Log, TestLoop, TestStorage, socketpair, wait_readable},
47    };
48
49    #[test]
50    #[cfg_attr(miri, ignore)]
51    fn joining_a_running_task_waits_for_it() {
52        let (rx, tx) = socketpair();
53        let mut selector = Selector::new().unwrap();
54        let mut event_loop = TestLoop::new(
55            {
56                static STORAGE: TestStorage = TestStorage::new();
57                &STORAGE
58            },
59            &mut selector,
60            Log::default(),
61            async move |ctx| {
62                ctx.spawn(async move |ctx| {
63                    wait_readable(&ctx, &rx).await;
64                    ctx.dispatch(1);
65                })
66                .await;
67                ctx.dispatch(2);
68            },
69        )
70        .unwrap();
71        assert!(event_loop.state_mut().events().is_empty());
72        event_loop.wake_by_writing(&tx);
73        assert_eq!(
74            event_loop.drain_events_without_blocking(),
75            Err(Error::RootFinished)
76        );
77        assert_eq!(event_loop.state_mut().events(), [1, 2]);
78    }
79
80    #[test]
81    #[cfg_attr(miri, ignore)]
82    fn joining_a_finished_task_resolves_immediately() {
83        let (rx, tx) = socketpair();
84        let mut selector = Selector::new().unwrap();
85        let mut event_loop = TestLoop::new(
86            {
87                static STORAGE: TestStorage = TestStorage::new();
88                &STORAGE
89            },
90            &mut selector,
91            Log::default(),
92            async move |ctx| {
93                let handle = ctx.spawn(async |ctx| ctx.dispatch(1));
94                wait_readable(&ctx, &rx).await;
95                handle.await;
96                ctx.dispatch(2);
97            },
98        )
99        .unwrap();
100        assert_eq!(event_loop.state_mut().events(), [1]);
101        event_loop.wake_by_writing(&tx);
102        assert_eq!(
103            event_loop.drain_events_without_blocking(),
104            Err(Error::RootFinished)
105        );
106        assert_eq!(event_loop.state_mut().events(), [1, 2]);
107    }
108
109    #[test]
110    #[cfg_attr(miri, ignore)]
111    fn dropped_handle_detaches_the_task() {
112        let (rx, tx) = socketpair();
113        let mut selector = Selector::new().unwrap();
114        let mut event_loop = TestLoop::new(
115            {
116                static STORAGE: TestStorage = TestStorage::new();
117                &STORAGE
118            },
119            &mut selector,
120            Log::default(),
121            async move |ctx| {
122                ctx.spawn(async move |ctx| {
123                    wait_readable(&ctx, &rx).await;
124                    ctx.dispatch(1);
125                });
126                pending::<()>().await;
127            },
128        )
129        .unwrap();
130        event_loop.wake_by_writing(&tx);
131        assert_eq!(event_loop.drain_events_without_blocking(), Ok(()));
132        assert_eq!(event_loop.state_mut().events(), [1]);
133    }
134
135    #[test]
136    #[cfg_attr(miri, ignore)]
137    fn spawned_task_can_spawn_and_join() {
138        let mut selector = Selector::new().unwrap();
139        let event_loop = TestLoop::new(
140            {
141                static STORAGE: TestStorage = TestStorage::new();
142                &STORAGE
143            },
144            &mut selector,
145            Log::default(),
146            async |ctx| {
147                ctx.spawn(async |ctx| {
148                    ctx.spawn(async |ctx| ctx.dispatch(1)).await;
149                    ctx.dispatch(2);
150                })
151                .await;
152                ctx.dispatch(3);
153                pending::<()>().await;
154            },
155        );
156        assert_eq!(event_loop.unwrap().state_mut().events(), [1, 2, 3]);
157    }
158}