Sub topic 14
How wakers tell the executor to poll again
This chapter assumes you know the Future trait and Poll from earlier chapters, plus basic threads and Arc. It explains what happens after a future returns Poll::Pending.
The problem: who polls next?
An executor calls poll on a future. If the future can't finish yet, it returns Poll::Pending. The executor can't keep polling in a loop, because that would burn CPU and defeat the purpose of async. It needs a signal that says "try this future again now."
That signal is the waker. A waker is a handle that, when called, tells the executor to schedule one specific task for another poll.
Where the waker lives: Context
Every poll call receives a &mut Context<'_>. Its waker() method returns a &Waker. The contract is:
- If
pollreturnsPending, the future must arrange for the waker to be called when progress is possible. - The executor will not poll that task again until the waker is called, though it may poll it earlier.
A future that returns Pending and never wakes anyone hangs forever. This is the most common bug in hand-written futures.
A future that wakes itself
The simplest valid future returns Pending once and asks to be polled again straight away:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct YieldOnce {
yielded: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
YieldOnce { yielded: false }.await;
println!("done");
}wake_by_ref puts the task back in the executor's queue. The second poll sees yielded == true and completes.
Waking from somewhere else
Real futures wait on something outside the executor: a socket, a timer, another thread. The future stores a clone of the waker where the event source can reach it. When the event happens, the source calls wake().
The diagram below shows the order of events.
Tokio's sleep and its sockets work this way. A timer or the operating system's event queue holds the waker and calls it when the deadline passes or data arrives.
Common errors
- Forgetting to wake. Returning
Pendingwithout registering the waker leaves the task asleep permanently. - Keeping a stale waker. A task can move between polls, and the
Contextmay carry a different waker next time. Update your stored waker on everyPendingreturn.Waker::will_wakelets you skip a clone when the waker is unchanged. - Waking in a busy loop. Calling
wake_by_refon every poll, asYieldOncedoes, is correct but spins the CPU if repeated. Use it only to yield briefly.
Exercise
A hand-written future returns Poll::Pending without storing or calling the waker. What happens to the task, and how do you fix it?
Show answer
The executor never polls the task again, so it hangs forever. Fix it by cloning cx.waker() and storing it where the event source can call wake() when the future can make progress. For an immediate retry, call cx.waker().wakebyref() before returning Pending.