Sub topic 15
How wakers tell the executor to poll again
This chapter assumes you know the Future trait and Poll from earlier in the tutorial. It also assumes you are comfortable with Arc, Mutex, and threads. By the end you will know what a waker is, who calls it, and why a future that returns Pending without arranging a wake-up can hang forever.
The problem wakers solve
An executor polls a future by calling poll. If the future is not finished, it returns Poll::Pending. The executor must then decide when to poll again.
There are two bad answers:
- Poll in a loop. This is called busy-polling. It burns a CPU core on futures that are only waiting for a timer or a socket.
- Never poll again. The future would never finish.
Rust's answer is a contract. When a future returns Pending, it promises to arrange for someone to call a waker when progress is possible. The executor then polls only the tasks that have been woken.
A waker is a handle to one task. Calling wake() on it tells the executor "this task is ready to be polled again". It does not run the task. It only schedules it.
Where the waker comes from
The executor passes the waker into every poll call, wrapped in a Context:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>You get the waker with cx.waker(), which returns &Waker. A Waker is cheap to clone. Cloning gives you an owned handle that you can move to another thread, an I/O driver, or a timer wheel.
When one future awaits another, the .await passes the same Context down. So the waker at the bottom of a chain of awaits always points to the top-level task, and waking it makes the executor poll the whole task from the top.
The two ways to wake
| Method | Takes | Use when |
|---|---|---|
| `wake()` | `self` (consumes the waker) | You are done with this waker, for example after taking it out of an `Option`. |
| `wake_by_ref()` | `&self` | You want to keep the waker, or you are waking from inside `poll`. |
Both do the same thing. The difference is only whether the waker is consumed.
Waking yourself: the yield-once future
The simplest legal future that returns Pending wakes itself first:
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
}
}
}On the first poll it asks to be polled again and returns Pending. This gives other tasks a turn before it continues. It is the same idea as tokio::task::yield_now.
Waking from another thread: a timer future
The more typical case is that the event comes from somewhere else. The future stores a waker, and the event source calls it.
The program below has a complete setup that uses only the standard library. It has a Timer future and a minimal block_on executor. The executor's waker unparks the thread that is running it.
use std::future::Future;
use std::pin::{pin, Pin};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread;
use std::time::{Duration, Instant};
struct Shared {
done: bool,
waker: Option<Waker>,
}
struct Timer {
shared: Arc<Mutex<Shared>>,
}
impl Timer {
fn new(dur: Duration) -> Self {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let thread_shared = Arc::clone(&shared);
thread::spawn(move || {
thread::sleep(dur);
let mut s = thread_shared.lock().unwrap();
s.done = true;
if let Some(w) = s.waker.take() {
w.wake();
}
});
Timer { shared }
}
}
impl Future for Timer {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.shared.lock().unwrap();
if s.done {
Poll::Ready(())
} else {
s.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
struct ThreadWaker(thread::Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
fn main() {
let start = Instant::now();
block_on(Timer::new(Duration::from_millis(200)));
println!("waited at least 200 ms: {}", start.elapsed() >= Duration::from_millis(200));
}It prints waited at least 200 ms: true. While it waits, the main thread is parked and uses no CPU.
The sequence of events is shown below.
Rules that keep futures correct
Store a waker on every Pending
Return Pending only after you have registered the current waker with whatever will signal progress. Without that, nothing will ever call wake, and the task hangs. The compiler cannot detect this mistake. The program just stops making progress.
Refresh the stored waker on every poll
A task can move between polls. For example, select! or a different executor thread may poll it, and the Context may carry a different waker. Always store the waker from the most recent poll, as the Timer does. A stale waker wakes the wrong thing or nothing.
You can avoid a clone when the waker has not changed:
use std::task::Waker;
fn store_waker(slot: &mut Option<Waker>, new: &Waker) {
match slot {
Some(old) if old.will_wake(new) => {}
_ => *slot = Some(new.clone()),
}
}will_wake is a best-effort check. It can return false for wakers that are in fact equivalent, so the fallback must always be safe.
Check the condition after storing the waker, or hold a lock
The Timer locks the mutex for the whole poll. The timer thread must lock the same mutex to set done. So the event cannot slip in between "check not done" and "store waker". If your design has no lock, store the waker first and then re-check the condition. Otherwise you can miss a wake-up that arrived in the gap.
Spurious polls are allowed
An executor may poll a future even when nobody woke it. poll must therefore check its real condition every time, and must not assume that being polled means the event happened.
What the executor does with a wake
Inside a real runtime such as Tokio, the waker for a task is a handle that pushes the task onto a run queue. A wake while the task is already queued does nothing extra. A wake while the task is running marks it to be polled again once the current poll returns. This is why waking is safe to call from any thread and at any time.
Wakers are Send and Sync, which is what lets I/O drivers and timer threads hold them.
Exercise
A future's poll checks a shared flag, sees it is not set, and returns Pending without storing cx.waker(). Another thread later sets the flag and the program hangs. Why, and what is the fix?
Show answer
The executor only polls a task again after its waker is called. The future never gave its waker to anyone, so nothing calls it, and the task is never polled again even though the flag is now set. The fix is to store cx.waker().clone() in shared state before returning Pending, and have the thread that sets the flag call wake() on the stored waker. The check and the store must be protected, for example by a mutex, so the flag cannot be set between them.
Exercise
Why should poll overwrite the stored waker on every call instead of storing it only on the first call?
Show answer
The task may be polled with a different waker later, for example after it moves to another executor thread or is combined with other futures in select!. If you keep the first waker, the later wake may go to the wrong place or nowhere, and the task can hang. Use will_wake to skip the clone when the waker has not changed.