Sub topic 6
Context and Waker: how a future asks to be polled again
This chapter assumes you know what Future and Poll are, and that an executor calls poll until a future returns Poll::Ready. It also assumes you can read basic trait and Arc code.
The problem: when should the executor poll again?
When poll returns Poll::Pending, the future is not finished. The executor could poll it again in a tight loop, but that burns CPU while it waits for a socket or a timer. The executor needs a way to sleep until something changes.
The Context and Waker types solve this. They let the future tell the executor, "poll me again, I may be able to make progress now."
What Context and Waker are
- A
Wakeris a handle that the executor creates. Callingwake()on it tells the executor to schedule the associated task for another poll. - A
Contextis a small wrapper that carries a&Waker. The executor passes it to everypollcall ascx: &mut Context<'_>.
A future reads the waker with cx.waker(). A Waker can be cloned and sent to other threads. A timer thread or an I/O reactor stores a clone and calls wake() when the event happens.
The contract
The rule is: if a future returns Pending, it must arrange for the waker to be called later. If it does not, nothing will ever poll it again, and the task hangs silently.
A future that is not ready has two options:
- Hand the waker to something that will call
wake()when the future can progress. - Call
wake_by_ref()right away, which asks for an immediate re-poll.
The CountDown future from the spine uses option 2:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct CountDown(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}Each poll decrements the counter, asks to be polled again, and returns Pending. This is fine for a demo. A real future would store the waker and let an external event trigger it, not wake itself in a loop.
Wakers can change between polls
The executor may pass a different waker on a later poll. If your future stores a waker, update it each time poll is called. A common pattern is to compare with will_wake and clone only if needed:
use std::task::{Context, Waker};
fn remember(slot: &mut Option<Waker>, cx: &Context<'_>) {
match slot {
Some(existing) if existing.will_wake(cx.waker()) => {}
_ => *slot = Some(cx.waker().clone()),
}
}Waking a stale waker can leave the current task asleep.
Common errors
- Returning
Pendingwithout registering the waker. The task never runs again. - Registering the waker only on the first poll. Later polls may use a new waker.
- Waking before the state is updated. The executor may poll before your data is ready, so set the state first and then call
wake().
Exercise
A hand-written future returns Poll::Pending and never touches cx.waker(). No other code holds a waker for it. What happens to the task, and how do you fix it?
Show answer
The task is never polled again, so it hangs. Fix it by making sure something will call wake() later: either hand a clone of cx.waker() to the event source that completes the work, or call cx.waker().wake_by_ref() before returning Pending if you want an immediate re-poll.