Skip to main content

rings_runtime/
task_set.rs

1//! A set of detached tasks whose end can be awaited.
2//!
3//! ```text
4//!   spawn   : TaskSet × F → Result (Joined F::Output) (Unscheduled F)    the task joins the set
5//!   drained : TaskSet → Future ()                                         no task of the set is live
6//! ```
7//!
8//! Law (liveness count): a task is live from its spawn until its future completes or is dropped
9//! (its executor shut down), and the set counts exactly its live tasks. [`TaskSet::drained`]
10//! resolves at an instant the count is zero, woken by the end of the last live task, never by
11//! time. A task spawned into the set by one of its live tasks is counted before its spawner
12//! ends, so a set whose tasks spawn only into it drains once every one of them, children
13//! included, is done.
14//!
15//! The set owns no task: as for [`spawn_detached`](crate::spawn_detached), the executor runs
16//! each task to its end, dropping a [`Joined`] abandons only the wait, and the set cancels
17//! nothing. A caller that must end its tasks gives them a way to end (a stop signal they
18//! observe) and then awaits [`TaskSet::drained`].
19
20use std::future::Future;
21use std::pin::Pin;
22use std::sync::Arc;
23use std::sync::Mutex;
24use std::sync::MutexGuard;
25use std::sync::PoisonError;
26use std::task::Context;
27use std::task::Poll;
28use std::task::Waker;
29
30use futures::channel::oneshot;
31
32use crate::bound::MaybeSend;
33use crate::task::Abandoned;
34use crate::task::Spawner;
35use crate::task::Unscheduled;
36
37/// A set of detached tasks whose end can be awaited (the liveness-count law).
38///
39/// Cloning shares the set: a task spawned through any clone is counted by all of them.
40#[derive(Clone, Default)]
41pub struct TaskSet {
42    live: Arc<Live>,
43}
44
45/// The live tasks of a set and the waiters of its drain.
46#[derive(Default)]
47struct Live {
48    state: Mutex<LiveState>,
49}
50
51/// The count of live tasks, and the wakers of the [`Drained`] futures that saw it above zero.
52#[derive(Default)]
53struct LiveState {
54    count: usize,
55    waiters: Vec<Waker>,
56}
57
58impl Live {
59    /// The state, under its lock. A poisoned lock still guards a well-formed state: no step
60    /// panics between two writes.
61    fn state(&self) -> MutexGuard<'_, LiveState> {
62        self.state.lock().unwrap_or_else(PoisonError::into_inner)
63    }
64}
65
66/// One live task's place in its set: counted while it lives, released when it is dropped, with
67/// the task's future or with the future the executor never polled.
68struct Membership(Arc<Live>);
69
70impl Membership {
71    /// Count one more live task in `live`.
72    fn join(live: &Arc<Live>) -> Self {
73        live.state().count += 1;
74        Self(Arc::clone(live))
75    }
76}
77
78impl Drop for Membership {
79    /// Count the task out, and wake every waiter of the drain if it was the last.
80    fn drop(&mut self) {
81        let waiters = {
82            let mut state = self.0.state();
83            state.count = state.count.saturating_sub(1);
84            if state.count == 0 {
85                std::mem::take(&mut state.waiters)
86            } else {
87                Vec::new()
88            }
89        };
90        waiters.into_iter().for_each(Waker::wake);
91    }
92}
93
94impl TaskSet {
95    /// An empty set.
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// Run `task` detached on the current executor as a member of this set.
101    ///
102    /// Post: `Ok` means the executor owns `task`, which is live in the set until it ends, and
103    /// the [`Joined`] resolves to its output, or to [`Abandoned`] if it is dropped first.
104    /// `Err` hands `task` back unpolled because no executor is current, and the set is
105    /// unchanged.
106    pub fn spawn<F>(&self, task: F) -> Result<Joined<F::Output>, Unscheduled<F>>
107    where
108        F: Future + MaybeSend + 'static,
109        F::Output: MaybeSend + 'static,
110    {
111        match Spawner::current() {
112            Ok(spawner) => Ok(self.spawn_with(&spawner, task)),
113            Err(_) => Err(Unscheduled(task)),
114        }
115    }
116
117    /// Run `task` detached on `spawner`'s executor as a member of this set: [`Self::spawn`]
118    /// for a caller that acquired the executor before claiming anything for the task.
119    ///
120    /// Post: as for [`Self::spawn`]'s `Ok`; if the executor has shut down, `task` is dropped
121    /// unpolled, leaves the set at once, and its [`Joined`] is [`Abandoned`].
122    pub fn spawn_with<F>(&self, spawner: &Spawner, task: F) -> Joined<F::Output>
123    where
124        F: Future + MaybeSend + 'static,
125        F::Output: MaybeSend + 'static,
126    {
127        let membership = Membership::join(&self.live);
128        let (sender, receiver) = oneshot::channel();
129        spawner.spawn(async move {
130            let _membership = membership;
131            // The receiver is gone only when the wait was abandoned; the task has run anyway.
132            let _ = sender.send(task.await);
133        });
134        Joined(receiver)
135    }
136
137    /// Resolves at an instant no task of this set is live (the liveness-count law).
138    pub fn drained(&self) -> Drained {
139        Drained(Arc::clone(&self.live))
140    }
141
142    /// How many tasks of this set are live now.
143    pub fn live(&self) -> usize {
144        self.live.state().count
145    }
146}
147
148/// The output of a task of a [`TaskSet`]: its value, or [`Abandoned`] if the task was dropped
149/// before it ended. Dropping it abandons only the wait.
150pub struct Joined<T>(oneshot::Receiver<T>);
151
152impl<T> Future for Joined<T> {
153    type Output = Result<T, Abandoned>;
154
155    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
156        Pin::new(&mut self.0).poll(cx).map_err(|_| Abandoned)
157    }
158}
159
160/// Resolves at an instant no task of its [`TaskSet`] is live.
161pub struct Drained(Arc<Live>);
162
163impl Future for Drained {
164    type Output = ();
165
166    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
167        let mut state = self.0.state();
168        if state.count == 0 {
169            return Poll::Ready(());
170        }
171        if !state.waiters.iter().any(|waiter| waiter.will_wake(cx.waker())) {
172            state.waiters.push(cx.waker().clone());
173        }
174        Poll::Pending
175    }
176}
177
178#[cfg(all(test, not(target_family = "wasm")))]
179mod test_task_set;