broker_tokio/task/
yield_now.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5doc_rt_core! {
6    /// Return a `Future` that can be `await`-ed to yield execution back to the
7    /// Tokio runtime.
8    ///
9    /// A task yields by awaiting the returned `Future`, and may resume when
10    /// that future completes (with no output.) The current task will be
11    /// re-added as a pending task at the _back_ of the pending queue. Any
12    /// other pending tasks will be scheduled. No other waking is required for
13    /// the task to continue.
14    ///
15    /// See also the usage example in the [task module](index.html#yield_now).
16    #[must_use = "yield_now does nothing unless polled/`await`-ed"]
17    pub async fn yield_now() {
18        /// Yield implementation
19        struct YieldNow {
20            yielded: bool,
21        }
22
23        impl Future for YieldNow {
24            type Output = ();
25
26            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
27                if self.yielded {
28                    return Poll::Ready(());
29                }
30
31                self.yielded = true;
32                cx.waker().wake_by_ref();
33                Poll::Pending
34            }
35        }
36
37        YieldNow { yielded: false }.await
38    }
39}