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        // Safety: nothing must be moved out of `futures`. This is to satisfy
133        // the requirement of `Pin::new_unchecked` called below.
134        //
135        // We can't use the `pin!` macro for this because `futures` is a tuple
136        // and the standard library provides no way to pin-project to the fields
137        // of a tuple.
138        let mut futures = ( $( $crate::macros::support::maybe_done($e), )* );
139
140        // This assignment makes sure that the `poll_fn` closure only has a
141        // reference to the futures, instead of taking ownership of them. This
142        // mitigates the issue described in
143        // <https://internals.rust-lang.org/t/surprising-soundness-trouble-around-pollfn/17484>
144        let mut futures = &mut futures;
145
146        // Each time the future created by poll_fn is polled, if not using biased mode,
147        // a different future is polled first to ensure every future passed to join!
148        // can make progress even if one of the futures consumes the whole budget.
149        let mut rotator = <$rotator_select as $crate::macros::support::RotatorSelect>::Rotator::<{$($total)*}>::default();
150
151        $crate::macros::support::poll_fn(move |cx| {
152            const COUNT: u32 = $($total)*;
153
154            let mut is_pending = false;
155            let mut to_run = COUNT;
156
157            // The number of futures that will be skipped in the first loop iteration.
158            let mut skip = rotator.num_skip();
159
160            // This loop runs twice and the first `skip` futures
161            // are not polled in the first iteration.
162            loop {
163            $(
164                if skip == 0 {
165                    if to_run == 0 {
166                        // Every future has been polled
167                        break;
168                    }
169                    to_run -= 1;
170
171                    // Extract the future for this branch from the tuple.
172                    let ( $($skip,)* fut, .. ) = &mut *futures;
173
174                    // Safety: future is stored on the stack above
175                    // and never moved.
176                    let mut fut = unsafe { $crate::macros::support::Pin::new_unchecked(fut) };
177
178                    // Try polling
179                    if $crate::macros::support::Future::poll(fut.as_mut(), cx).is_pending() {
180                        is_pending = true;
181                    }
182                } else {
183                    // Future skipped, one less future to skip in the next iteration
184                    skip -= 1;
185                }
186            )*
187            }
188
189            if is_pending {
190                $crate::macros::support::Poll::Pending
191            } else {
192                $crate::macros::support::Poll::Ready(($({
193                    // Extract the future for this branch from the tuple.
194                    let ( $($skip,)* fut, .. ) = &mut futures;
195
196                    // Safety: future is stored on the stack above
197                    // and never moved.
198                    let mut fut = unsafe { $crate::macros::support::Pin::new_unchecked(fut) };
199
200                    fut.take_output().expect("expected completed future")
201                },)*))
202            }
203        }).await
204    }};
205
206    // ===== Normalize =====
207
208    (@ { rotator_select=$rotator_select:ty; ( $($s:tt)* ) ( $($n:tt)* ) $($t:tt)* } $e:expr, $($r:tt)* ) => {
209        $crate::join!(@{ rotator_select=$rotator_select; ($($s)* _) ($($n)* + 1) $($t)* ($($s)*) $e, } $($r)*)
210    };
211
212    // ===== Entry point =====
213    ( biased; $($e:expr),+ $(,)?) => {
214        $crate::join!(@{ rotator_select=$crate::macros::support::SelectBiased; () (0) } $($e,)*)
215    };
216
217    ( $($e:expr),+ $(,)?) => {
218        $crate::join!(@{ rotator_select=$crate::macros::support::SelectNormal; () (0) } $($e,)*)
219    };
220
221    (biased;) => { async {}.await };
222
223    () => { async {}.await }
224}}
225
226/// Helper trait to select which type of `Rotator` to use.
227// We need this to allow specifying a const generic without
228// colliding with caller const names due to macro hygiene.
229pub trait RotatorSelect {
230    type Rotator<const COUNT: u32>: Default;
231}
232
233/// Marker type indicating that the starting branch should
234/// rotate each poll.
235#[derive(Debug)]
236pub struct SelectNormal;
237/// Marker type indicating that the starting branch should
238/// be the first declared branch each poll.
239#[derive(Debug)]
240pub struct SelectBiased;
241
242impl RotatorSelect for SelectNormal {
243    type Rotator<const COUNT: u32> = Rotator<COUNT>;
244}
245
246impl RotatorSelect for SelectBiased {
247    type Rotator<const COUNT: u32> = BiasedRotator;
248}
249
250/// Rotates by one each [`Self::num_skip`] call up to COUNT - 1.
251#[derive(Default, Debug)]
252pub struct Rotator<const COUNT: u32> {
253    next: u32,
254}
255
256impl<const COUNT: u32> Rotator<COUNT> {
257    /// Rotates by one each [`Self::num_skip`] call up to COUNT - 1
258    #[inline]
259    pub fn num_skip(&mut self) -> u32 {
260        let num_skip = self.next;
261        self.next += 1;
262        if self.next == COUNT {
263            self.next = 0;
264        }
265        num_skip
266    }
267}
268
269/// [`Self::num_skip`] always returns 0.
270#[derive(Default, Debug)]
271pub struct BiasedRotator {}
272
273impl BiasedRotator {
274    /// Always returns 0.
275    #[inline]
276    pub fn num_skip(&mut self) -> u32 {
277        0
278    }
279}