Skip to main content

externally_driven_async_rt/tasks/
task_reservation.rs

1use crate::{
2    claimed::Claimed,
3    tasks::{TaskEntry, TaskId, Tasks},
4};
5
6/// A task reservation that can be used to spawn a task without waiting for a free slot.
7#[must_use = "a reservation holds a task slot until it is spawned into or dropped"]
8pub struct TaskReservation<
9    'sel,
10    const TASKS: usize,
11    const TASK_SIZE: usize,
12    const ROOT_TASK_SIZE: usize,
13> {
14    tasks: &'static Tasks<TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
15    claimed: Claimed<'sel>,
16    id: TaskId<TASK_SIZE>,
17    entry: &'static TaskEntry<TASK_SIZE>,
18}
19
20impl<'sel, const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize>
21    TaskReservation<'sel, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
22{
23    pub(super) const fn new(
24        tasks: &'static Tasks<TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
25        claimed: Claimed<'sel>,
26        id: TaskId<TASK_SIZE>,
27        entry: &'static TaskEntry<TASK_SIZE>,
28    ) -> Self {
29        Self {
30            tasks,
31            claimed,
32            id,
33            entry,
34        }
35    }
36
37    /// Spawns a task using a reserved slot that is held by this [`TaskReservation`].
38    ///
39    /// The future must fit `TASK_SIZE` bytes and be aligned to at most 16 bytes, otherwise the
40    /// program doesn't compile.
41    ///
42    /// Returns a join handle, a future that resolves once the task is finished. Dropping it
43    /// detaches the task, which keeps running until it finishes.
44    pub fn spawn<Fut>(
45        self,
46        future: Fut,
47    ) -> impl Future<Output = ()> + use<TASKS, TASK_SIZE, ROOT_TASK_SIZE, Fut>
48    where
49        Fut: Future<Output = ()> + 'sel,
50    {
51        let Self {
52            tasks,
53            claimed,
54            id,
55            entry,
56        } = self;
57        tasks.spawn_reserved(claimed, id, entry, future);
58        core::mem::forget(self);
59        tasks.join(id)
60    }
61}
62
63impl<const TASKS: usize, const TASK_SIZE: usize, const ROOT_TASK_SIZE: usize> Drop
64    for TaskReservation<'_, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
65{
66    fn drop(&mut self) {
67        self.tasks.release(self.id);
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use core::{
74        future::{Future, pending},
75        pin::pin,
76        sync::atomic::{AtomicBool, Ordering::Relaxed},
77        task::{Context, Poll, Waker},
78    };
79
80    use crate::{
81        NotEnoughResources,
82        tasks::{TaskReservation, Tasks},
83        testing::claimed_forever,
84    };
85
86    #[test]
87    fn spawning_runs_the_task() {
88        static TASKS: Tasks<1, 64, 0> = Tasks::new();
89        static RAN: AtomicBool = AtomicBool::new(false);
90        let (id, entry) = TASKS.pool.alloc().unwrap();
91        let mut handle = pin!(
92            TaskReservation::new(&TASKS, claimed_forever(), id, entry)
93                .spawn(async { RAN.store(true, Relaxed) })
94        );
95        let _ = TASKS.run_ready();
96        assert!(RAN.load(Relaxed));
97        let mut cx = Context::from_waker(Waker::noop());
98        assert_eq!(handle.as_mut().poll(&mut cx), Poll::Ready(()));
99    }
100
101    #[test]
102    fn dropping_frees_the_slot_and_wakes_the_waiter() {
103        static TASKS: Tasks<2, 64, 0> = Tasks::new();
104        assert!(TASKS.queue.claim().is_some());
105        let waiter = TASKS.spawn_task(claimed_forever(), pending()).unwrap();
106        let _ = TASKS.run_ready();
107        let (id, entry) = TASKS.pool.alloc().unwrap();
108        let reservation = TaskReservation::new(&TASKS, claimed_forever(), id, entry);
109        let mut reserve = pin!(TASKS.reserve(claimed_forever()));
110        let waker = TASKS.queue.waker(waiter.idx);
111        let mut cx = Context::from_waker(&waker);
112        assert!(reserve.as_mut().poll(&mut cx).is_pending());
113        drop(reservation);
114        assert!(!TASKS.queue.is_empty());
115        assert!(reserve.as_mut().poll(&mut cx).is_ready());
116    }
117
118    #[test]
119    fn a_reserved_slot_is_not_handed_to_spawn() {
120        static TASKS: Tasks<1, 64, 0> = Tasks::new();
121        let (id, entry) = TASKS.pool.alloc().unwrap();
122        let _reservation = TaskReservation::new(&TASKS, claimed_forever(), id, entry);
123        assert_eq!(
124            TASKS.spawn_task(claimed_forever(), async {}),
125            Err(NotEnoughResources::Tasks)
126        );
127    }
128}