tokio/macros/
join.rs

1macro_rules! doc {
2    ($join:item) => {
3        /// Waits on multiple concurrent branches, returning when **all** branches
4        /// complete.
5        ///
6        /// The `join!` macro must be used inside of async functions, closures, and
7        /// blocks.
8        ///
9        /// The `join!` macro takes a list of async expressions and evaluates them
10        /// concurrently on the same task. Each async expression evaluates to a future
11        /// and the futures from each expression are multiplexed on the current task.
12        ///
13        /// When working with async expressions returning `Result`, `join!` will wait
14        /// for **all** branches complete regardless if any complete with `Err`. Use
15        /// [`try_join!`] to return early when `Err` is encountered.
16        ///
17        /// [`try_join!`]: crate::try_join
18        ///
19        /// # Notes
20        ///
21        /// The supplied futures are stored inline and do not require allocating a
22        /// `Vec`.
23        ///
24        /// ## Runtime characteristics
25        ///
26        /// By running all async expressions on the current task, the expressions are
27        /// able to run **concurrently** but not in **parallel**. This means all
28        /// expressions are run on the same thread and if one branch blocks the thread,
29        /// all other expressions will be unable to continue. If parallelism is
30        /// required, spawn each async expression using [`tokio::spawn`] and pass the
31        /// join handle to `join!`.
32        ///
33        /// [`tokio::spawn`]: crate::spawn
34        ///
35        /// ## Fairness
36        ///
37        /// By default, `join!`'s generated future rotates which contained
38        /// future is polled first whenever it is woken.
39        ///
40        /// This behavior can be overridden by adding `biased;` to the beginning of the
41        /// macro usage. See the examples for details. This will cause `join` to poll
42        /// the futures in the order they appear from top to bottom.
43        ///
44        /// You may want this if your futures may interact in a way where known polling order is significant.
45        ///
46        /// But there is an important caveat to this mode. It becomes your responsibility
47        /// to ensure that the polling order of your futures is fair. If for example you
48        /// are joining a stream and a shutdown future, and the stream has a
49        /// huge volume of messages that takes a long time to finish processing per poll, you should
50        /// place the shutdown future earlier in the `join!` list to ensure that it is
51        /// always polled, and will not be delayed due to the stream future taking a long time to return
52        /// `Poll::Pending`.
53        ///
54        /// # Examples
55        ///
56        /// Basic join with two branches
57        ///
58        /// ```
59        /// async fn do_stuff_async() {
60        ///     // async work
61        /// }
62        ///
63        /// async fn more_async_work() {
64        ///     // more here
65        /// }
66        ///
67        /// # #[tokio::main(flavor = "current_thread")]
68        /// # async fn main() {
69        /// let (first, second) = tokio::join!(
70        ///     do_stuff_async(),
71        ///     more_async_work());
72        ///
73        /// // do something with the values
74        /// # }
75        /// ```
76        ///
77        /// Using the `biased;` mode to control polling order.
78        ///
79        /// ```
80        /// # #[cfg(not(target_family = "wasm"))]
81        /// # {
82        /// async fn do_stuff_async() {
83        ///     // async work
84        /// }
85        ///
86        /// async fn more_async_work() {
87        ///     // more here
88        /// }
89        ///
90        /// # #[tokio::main(flavor = "current_thread")]
91        /// # async fn main() {
92        /// let (first, second) = tokio::join!(
93        ///     biased;
94        ///     do_stuff_async(),
95        ///     more_async_work()
96        /// );
97        ///
98        /// // do something with the values
99        /// # }
100        /// # }
101        /// ```
102
103        #[macro_export]
104        #[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
105        $join
106    };
107}
108
109#[cfg(doc)]
110doc! {macro_rules! join {
111    ($(biased;)? $($future:expr),*) => { unimplemented!() }
112}}
113
114#[cfg(not(doc))]
115doc! {macro_rules! join {
116    (@ {
117        // Type of rotator that controls which inner future to start with
118        // when polling our output future.
119        rotator_select=$rotator_select:ty;
120
121        // One `_` for each branch in the `join!` macro. This is not used once
122        // normalization is complete.
123        ( $($count:tt)* )
124
125        // The expression `0+1+1+ ... +1` equal to the number of branches.
126        ( $($total:tt)* )
127
128        // Normalized join! branches
129        $( ( $($skip:tt)* ) $e:expr, )*
130
131    }) => {{
132        use $crate::macros::support::{maybe_done, poll_fn, Future, Pin, RotatorSelect};
133        use $crate::macros::support::Poll::{Ready, Pending};
134
135        // Safety: nothing must be moved out of `futures`. This is to satisfy
136        // the requirement of `Pin::new_unchecked` called below.
137        //
138        // We can't use the `pin!` macro for this because `futures` is a tuple
139        // and the standard library provides no way to pin-project to the fields
140        // of a tuple.
141        let mut futures = ( $( maybe_done($e), )* );
142
143        // This assignment makes sure that the `poll_fn` closure only has a
144        // reference to the futures, instead of taking ownership of them. This
145        // mitigates the issue described in
146        // <https://internals.rust-lang.org/t/surprising-soundness-trouble-around-pollfn/17484>
147        let mut futures = &mut futures;
148
149        // Each time the future created by poll_fn is polled, if not using biased mode,
150        // a different future is polled first to ensure every future passed to join!
151        // can make progress even if one of the futures consumes the whole budget.
152        let mut rotator = <$rotator_select as RotatorSelect>::Rotator::<{$($total)*}>::default();
153
154        poll_fn(move |cx| {
155            const COUNT: u32 = $($total)*;
156
157            let mut is_pending = false;
158            let mut to_run = COUNT;
159
160            // The number of futures that will be skipped in the first loop iteration.
161            let mut skip = rotator.num_skip();
162
163            // This loop runs twice and the first `skip` futures
164            // are not polled in the first iteration.
165            loop {
166            $(
167                if skip == 0 {
168                    if to_run == 0 {
169                        // Every future has been polled
170                        break;
171                    }
172                    to_run -= 1;
173
174                    // Extract the future for this branch from the tuple.
175                    let ( $($skip,)* fut, .. ) = &mut *futures;
176
177                    // Safety: future is stored on the stack above
178                    // and never moved.
179                    let mut fut = unsafe { Pin::new_unchecked(fut) };
180
181                    // Try polling
182                    if fut.poll(cx).is_pending() {
183                        is_pending = true;
184                    }
185                } else {
186                    // Future skipped, one less future to skip in the next iteration
187                    skip -= 1;
188                }
189            )*
190            }
191
192            if is_pending {
193                Pending
194            } else {
195                Ready(($({
196                    // Extract the future for this branch from the tuple.
197                    let ( $($skip,)* fut, .. ) = &mut futures;
198
199                    // Safety: future is stored on the stack above
200                    // and never moved.
201                    let mut fut = unsafe { Pin::new_unchecked(fut) };
202
203                    fut.take_output().expect("expected completed future")
204                },)*))
205            }
206        }).await
207    }};
208
209    // ===== Normalize =====
210
211    (@ { rotator_select=$rotator_select:ty; ( $($s:tt)* ) ( $($n:tt)* ) $($t:tt)* } $e:expr, $($r:tt)* ) => {
212        $crate::join!(@{ rotator_select=$rotator_select; ($($s)* _) ($($n)* + 1) $($t)* ($($s)*) $e, } $($r)*)
213    };
214
215    // ===== Entry point =====
216    ( biased; $($e:expr),+ $(,)?) => {
217        $crate::join!(@{ rotator_select=$crate::macros::support::SelectBiased; () (0) } $($e,)*)
218    };
219
220    ( $($e:expr),+ $(,)?) => {
221        $crate::join!(@{ rotator_select=$crate::macros::support::SelectNormal; () (0) } $($e,)*)
222    };
223
224    (biased;) => { async {}.await };
225
226    () => { async {}.await }
227}}
228
229/// Helper trait to select which type of `Rotator` to use.
230// We need this to allow specifying a const generic without
231// colliding with caller const names due to macro hygiene.
232pub trait RotatorSelect {
233    type Rotator<const COUNT: u32>: Default;
234}
235
236/// Marker type indicating that the starting branch should
237/// rotate each poll.
238#[derive(Debug)]
239pub struct SelectNormal;
240/// Marker type indicating that the starting branch should
241/// be the first declared branch each poll.
242#[derive(Debug)]
243pub struct SelectBiased;
244
245impl RotatorSelect for SelectNormal {
246    type Rotator<const COUNT: u32> = Rotator<COUNT>;
247}
248
249impl RotatorSelect for SelectBiased {
250    type Rotator<const COUNT: u32> = BiasedRotator;
251}
252
253/// Rotates by one each [`Self::num_skip`] call up to COUNT - 1.
254#[derive(Default, Debug)]
255pub struct Rotator<const COUNT: u32> {
256    next: u32,
257}
258
259impl<const COUNT: u32> Rotator<COUNT> {
260    /// Rotates by one each [`Self::num_skip`] call up to COUNT - 1
261    #[inline]
262    pub fn num_skip(&mut self) -> u32 {
263        let num_skip = self.next;
264        self.next += 1;
265        if self.next == COUNT {
266            self.next = 0;
267        }
268        num_skip
269    }
270}
271
272/// [`Self::num_skip`] always returns 0.
273#[derive(Default, Debug)]
274pub struct BiasedRotator {}
275
276impl BiasedRotator {
277    /// Always returns 0.
278    #[inline]
279    pub fn num_skip(&mut self) -> u32 {
280        0
281    }
282}