Skip to main content

externally_driven_async_rt/tasks/
task_reservation.rs

1use crate::{
2    context::Context,
3    state::State,
4    storage::LoopStorageGuard,
5    tasks::{JoinHandle, TaskId},
6};
7
8/// A task reservation that can be used to spawn a task without waiting for a free slot.
9#[must_use = "a reservation holds a task slot until it is spawned into or dropped"]
10pub struct TaskReservation<
11    'a,
12    S: State,
13    const TASKS: usize,
14    const TASK_SIZE: usize,
15    const ROOT_TASK_SIZE: usize,
16    const TIMERS: usize,
17    const FDS: usize,
18> {
19    storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
20    id: TaskId,
21}
22
23impl<
24    'a,
25    S: State,
26    const TASKS: usize,
27    const TASK_SIZE: usize,
28    const ROOT_TASK_SIZE: usize,
29    const TIMERS: usize,
30    const FDS: usize,
31> TaskReservation<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
32{
33    pub(crate) fn new(
34        storage: LoopStorageGuard<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
35        id: TaskId,
36    ) -> Self {
37        Self { storage, id }
38    }
39
40    /// Spawns a task using a reserved slot that is held by this [`TaskReservation`].
41    ///
42    /// # Panics
43    ///
44    /// Panics if:
45    ///
46    /// 1. the future is bigger than `TASK_SIZE` bytes
47    /// 2. it is aligned to more than 16 bytes.
48    pub fn spawn<F, Fut>(self, f: F) -> JoinHandle<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>
49    where
50        F: FnOnce(Context<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>) -> Fut,
51        Fut: Future<Output = ()> + 'a,
52    {
53        let Self { storage, id } = self;
54        storage.tasks().spawn_reserved(id, f(Context::new(storage)));
55        core::mem::forget(self);
56        JoinHandle::new(storage.tasks(), id)
57    }
58}
59
60impl<
61    S: State,
62    const TASKS: usize,
63    const TASK_SIZE: usize,
64    const ROOT_TASK_SIZE: usize,
65    const TIMERS: usize,
66    const FDS: usize,
67> Drop for TaskReservation<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
68{
69    fn drop(&mut self) {
70        self.storage.tasks().release(self.id);
71    }
72}
73
74impl<
75    'a,
76    S: State,
77    const TASKS: usize,
78    const TASK_SIZE: usize,
79    const ROOT_TASK_SIZE: usize,
80    const TIMERS: usize,
81    const FDS: usize,
82> core::fmt::Debug for TaskReservation<'a, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
83{
84    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
85        f.write_str("TaskReservation")
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use core::{future::pending, time::Duration};
92
93    use crate::{
94        Selector,
95        testing::{EventLoopTestingExt, Log, TEST_TASKS, TestLoop, TestStorage},
96    };
97
98    #[test]
99    #[cfg_attr(miri, ignore)]
100    fn spawning_runs_the_task() {
101        let mut selector = Selector::new().unwrap();
102        let mut event_loop = TestLoop::new(
103            {
104                static STORAGE: TestStorage = TestStorage::new();
105                &STORAGE
106            },
107            &mut selector,
108            Log::default(),
109            async |ctx| {
110                let task = ctx.reserve_task().await;
111                task.spawn(async |ctx| ctx.dispatch(1)).await;
112                ctx.dispatch(2);
113                pending::<()>().await;
114            },
115        )
116        .unwrap();
117        assert_eq!(event_loop.state_mut().events(), [1, 2]);
118    }
119
120    #[test]
121    #[cfg_attr(miri, ignore)]
122    fn dropping_frees_the_slot_and_wakes_the_waiter() {
123        let mut selector = Selector::new().unwrap();
124        let mut event_loop = TestLoop::new(
125            {
126                static STORAGE: TestStorage = TestStorage::new();
127                &STORAGE
128            },
129            &mut selector,
130            Log::default(),
131            async |ctx| {
132                for _ in 0..TEST_TASKS - 3 {
133                    ctx.spawn(async |_| pending::<()>().await);
134                }
135                let task = ctx.reserve_task().await;
136                ctx.spawn(async |ctx| {
137                    let _task = ctx.reserve_task().await;
138                    ctx.dispatch(2);
139                    pending::<()>().await;
140                });
141                ctx.sleep(Duration::from_millis(1)).await;
142                ctx.dispatch(1);
143                drop(task);
144                pending::<()>().await;
145            },
146        )
147        .unwrap();
148        assert!(event_loop.state_mut().events().is_empty());
149        event_loop.run_until_events(2);
150        assert_eq!(event_loop.state_mut().events(), [1, 2]);
151    }
152
153    #[test]
154    #[cfg_attr(miri, ignore)]
155    #[should_panic(expected = "more than 16 concurrent tasks")]
156    fn a_reserved_slot_is_not_handed_to_spawn() {
157        let mut selector = Selector::new().unwrap();
158        let _ = TestLoop::new(
159            {
160                static STORAGE: TestStorage = TestStorage::new();
161                &STORAGE
162            },
163            &mut selector,
164            Log::default(),
165            async |ctx| {
166                for _ in 0..TEST_TASKS - 2 {
167                    ctx.spawn(async |_| pending::<()>().await);
168                }
169                let _task = ctx.reserve_task().await;
170                ctx.spawn(async |_| {});
171            },
172        );
173    }
174}