tokio/task/yield_now.rs
1use crate::runtime::context;
2
3use std::future::poll_fn;
4use std::task::{ready, Poll};
5
6/// Yields execution back to the Tokio runtime.
7///
8/// A task yields by awaiting on `yield_now()`, and may resume when that future
9/// completes (with no output.) The current task will be re-added as a pending
10/// task at the _back_ of the pending queue. Any other pending tasks will be
11/// scheduled. No other waking is required for the task to continue.
12///
13/// See also the usage example in the [task module](index.html#yield_now).
14///
15/// ## Non-guarantees
16///
17/// This function may not yield all the way up to the executor if there are any
18/// special combinators above it in the call stack. For example, if a
19/// [`tokio::select!`] has another branch complete during the same poll as the
20/// `yield_now()`, then the yield is not propagated all the way up to the
21/// runtime.
22///
23/// It is generally not guaranteed that the runtime behaves like you expect it
24/// to when deciding which task to schedule next after a call to `yield_now()`.
25/// In particular, the runtime may choose to poll the task that just ran
26/// `yield_now()` again immediately without polling any other tasks first. For
27/// example, the runtime will not drive the IO driver between every poll of a
28/// task, and this could result in the runtime polling the current task again
29/// immediately even if there is another task that could make progress if that
30/// other task is waiting for a notification from the IO driver.
31///
32/// In general, changes to the order in which the runtime polls tasks is not
33/// considered a breaking change, and your program should be correct no matter
34/// which order the runtime polls your tasks in.
35///
36/// [`tokio::select!`]: macro@crate::select
37#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
38pub async fn yield_now() {
39 let mut yielded = false;
40 poll_fn(|cx| {
41 ready!(crate::trace::trace_leaf(cx));
42
43 if yielded {
44 return Poll::Ready(());
45 }
46
47 yielded = true;
48
49 context::defer(cx.waker());
50
51 Poll::Pending
52 })
53 .await
54}