Sub topic 6
Context and Waker: how a future asks to be polled again
This chapter assumes you know the Future trait, Poll::Ready and Poll::Pending, and what Arc and Mutex do. You should also be comfortable reading Pin<&mut Self> in a poll signature, even if you don't yet know why it is there.
The problem: when should poll run again?
An executor calls poll on a future. If the future isn't ready, it returns Poll::Pending. The executor now has to decide when to call poll again.
The simplest answer is to poll in a loop. That burns a CPU core while a task waits for a socket or a timer. It also starves every other task.
Rust's answer is that the future tells the executor when to poll it again. The executor hands the future a Waker on every poll. The future stores it and calls it when something changes. Until then the executor can do other work or put the thread to sleep.
Context and Waker
poll takes a &mut Context<'_>. A Context is a thin wrapper around a &Waker. You get the waker with cx.waker().
A Waker is a handle to one task. It has a few operations:
| Method | What it does |
|---|---|
| `wake(self)` | Consumes the waker and schedules the task to be polled again. |
| `wake_by_ref(&self)` | Does the same without consuming it. |
| `clone()` | Makes another handle to the same task. This is how you keep a waker after `poll` returns. |
| `will_wake(&self, other)` | Returns `true` if two wakers would wake the same task. It is a cheap check that may give false negatives. |
A Waker is Send + Sync. That lets you move it to another thread, such as a timer thread or an I/O driver, and call it from there.
A Context borrows the waker only for the duration of one poll call. You can't keep the &Waker it gives you. If you need the waker later, clone it.
The contract
Whenever poll returns Poll::Pending, the future must have arranged for the waker from that call to be woken when progress becomes possible.
If it doesn't, nothing breaks loudly. The executor sees Pending, assumes a wake-up is coming, and parks. The task then hangs forever. This is the most common bug in hand-written futures.
The contract has a few consequences:
- A future may be polled when nothing has changed (a spurious poll), so
pollmust re-check the real state each time. - A wake-up may arrive when the future is already finished or dropped. This is harmless.
- Only the most recent waker matters. If a future is moved to a different task, for example inside a
join, the next poll supplies a different waker, and the old one is stale.
The CountDown future in the spine takes the simplest route. It calls cx.waker().wake_by_ref() before returning Pending, which says "poll me again right away". That satisfies the contract, but it spins. Real leaf futures hand the waker to whatever will produce the event.
Flow of a wake-up
The diagram shows the usual sequence for a future waiting on an external event.
A future that stores its waker
This future completes when another party calls fire. The state it shares with that party holds a done flag and the latest waker.
use std::future::Future;
use std::pin::{pin, Pin};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
struct Shared {
done: bool,
waker: Option<Waker>,
}
struct Signal {
shared: Arc<Mutex<Shared>>,
}
impl Future for Signal {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.shared.lock().unwrap();
if s.done {
return Poll::Ready(());
}
let up_to_date = matches!(&s.waker, Some(w) if w.will_wake(cx.waker()));
if !up_to_date {
s.waker = Some(cx.waker().clone());
}
Poll::Pending
}
}
fn fire(shared: &Arc<Mutex<Shared>>) {
let waker = {
let mut s = shared.lock().unwrap();
s.done = true;
s.waker.take()
};
if let Some(w) = waker {
w.wake();
}
}
struct CountingWaker(AtomicUsize);
impl Wake for CountingWaker {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
fn main() {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let fut = Signal { shared: shared.clone() };
let mut fut = pin!(fut);
let counter = Arc::new(CountingWaker(AtomicUsize::new(0)));
let waker = Waker::from(counter.clone());
let mut cx = Context::from_waker(&waker);
assert_eq!(fut.as_mut().poll(&mut cx), Poll::Pending);
assert_eq!(counter.0.load(Ordering::SeqCst), 0);
fire(&shared);
assert_eq!(counter.0.load(Ordering::SeqCst), 1);
assert_eq!(fut.as_mut().poll(&mut cx), Poll::Ready(()));
println!("woken {} time(s)", counter.0.load(Ordering::SeqCst));
}This program has no executor. main plays the executor by hand: it builds a Waker from any type that implements Wake, and wraps it in a Context with Context::from_waker. Running it prints woken 1 time(s).
A few details in the code matter:
pollchecksdoneand stores the waker while holding the same lock. That prevents a lost wake-up. If the check and the store were separate steps,firecould run between them. It would setdoneand find no waker to call, and the future would then store a waker nobody ever wakes.will_wakeavoids a clone when the executor passes the same waker again. When the check says no, the old waker is replaced, which handles the stale-waker case.firereleases the lock before callingwake. Some executors poll inline insidewake, and that would try to lock the mutex again and deadlock.SignalisUnpin, becauseArcisUnpin. That is whyself.sharedcan be read throughPin<&mut Self>without anyunsafe.
Common mistakes
- Returning
Pendingwithout registering a waker. The task hangs. Check everyPendingpath, including the "still waiting" branch of a state machine. - Waking before storing state. If you call
wakebefore the data that makes the future ready is visible, the next poll sees nothing new and returnsPendingagain with nothing to wake it. - Storing the first waker forever. Futures that get moved between tasks or wrapped by combinators receive different wakers over time. Always update the stored waker on each poll.
- Holding a lock while waking. See the deadlock note above.
- Assuming one wake equals one poll. Executors may coalesce several wakes into one poll, and may poll without any wake. Treat
pollas "check everything again".
Exercises
Exercise
A hand-written future checks whether data has arrived. If it hasn't, it returns Poll::Pending and does not store or call the waker. The data arrives a moment later. What happens to the task, and why?
Show answer
The task hangs. The executor received Pending, so it stops polling the task until a wake-up arrives. Nothing ever calls the waker, so the future is never polled again and never sees the data. The fix is to clone cx.waker() into the shared state before returning Pending, and to have the producer wake it after publishing the data.
Exercise
In Signal::poll, suppose the code first returned Pending after checking done under the lock, and only afterwards locked again to store the waker. Describe an interleaving that loses the wake-up.
Show answer
The poll thread checks done (false) and releases the lock. Another thread then runs fire: it sets done = true, finds waker empty, and has nothing to wake. The poll thread then locks again and stores its waker, and returns Pending. No further wake will ever come, so the task hangs even though done is true. Checking and storing under one lock guard rules this out.