Sub topic 2
How futures are polled: Poll and Waker
This chapter assumes you know what async fn and .await give you, and that you are comfortable with traits and Pin at a basic level. It shows what happens underneath an .await.
A future is a state machine you poll
An async fn returns a value that implements the Future trait. Calling the function does not run any of its body. Something has to call the future's poll method:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>Poll is an enum with two variants:
Poll::Ready(value)means the future finished and producedvalue.Poll::Pendingmeans the future cannot make progress yet.
The compiler turns each async body into a state machine. Each .await becomes a point where the machine can return Pending and later resume from the same spot.
The Waker prevents busy-polling
If a future returns Pending, the executor must not poll it again in a tight loop, because that wastes CPU. Instead, the Context passed to poll holds a Waker. Before returning Pending, a future must arrange for cx.waker().wake() to be called once progress is possible. A timer, a socket becoming readable, or another task sending a message can all trigger that call. The wake tells the executor to schedule the task for another poll.
A hand-written future
This future returns Pending three times, then Ready. Each time, it asks to be woken immediately. A real future would hand the waker to a timer or socket instead.
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("liftoff")
} else {
println!("polled, {} left", self.0);
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
println!("{}", Countdown(3).await);
}The output is three polled lines (3, 2, 1 left), then liftoff. If you remove the wake_by_ref call, the program hangs. The future returned Pending, nothing ever woke it, and the executor correctly left it asleep.
Common errors
- Returning
Pendingwithout registering a waker. The task never runs again. This is the most common bug in hand-written futures. - Keeping a stale waker. The executor may hand a different waker on each poll. Replace the stored one if
will_wakesays it differs. - Blocking inside
poll.pollmust return quickly. A long computation or a blocking call stalls every task on that worker thread. - Polling a future after it returned
Ready. The trait allows it to panic..awaitnever does this.
Why this matters for Tokio
Tokio's timers, sockets and channels are futures that follow this contract. The reactor stores the waker, and the executor re-polls the task after it is woken. A task that is not awake costs no CPU. This is why one thread can serve thousands of idle connections.
Exercise
In the Countdown example, what happens if poll returns Poll::Pending but never calls the waker, and why?
Show answer
The task hangs forever. The executor only polls a task again after its waker is called. With no wake, the task stays asleep and its output is never produced.
Exercise
Why must a future never block inside poll?
Show answer
poll runs on an executor worker thread. If it blocks, that thread cannot poll any other task, so unrelated tasks stall until the call returns.