Sub topic 3
Polling: Poll::Ready and Poll::Pending
This chapter covers the Poll enum and the contract around Future::poll. It assumes you know Rust enums and pattern matching, can read trait signatures, and have seen Future described as a value that may not be ready yet. Wakers get a short mention here and a full chapter later.
The Poll enum
Future::poll has one job: report whether the value is ready. The answer is a two-variant enum from std::task:
pub enum Poll<T> {
Ready(T),
Pending,
}The full method signature is:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;Three things matter here:
Poll::Ready(value)means the future is finished andvalueis its output.Poll::Pendingmeans the future cannot finish yet. It does not report an error or a failure.polltakesPin<&mut Self>, notself. A future is polled many times, sopollmust borrow it. ThePinwrapper is explained in later chapters. For now, read it as&mut Selfwith a promise that the value will not move.
Poll<T> looks like Option<T>, but the variants mean something different. Pending is not "no value". It means "ask me again later".
Driving a future by hand
A future does nothing until something polls it. This program polls a hand-written future three times and prints each answer. It needs Rust 1.85 or newer for Waker::noop.
use std::future::Future;
use std::pin::{pin, Pin};
use std::task::{Context, Poll, Waker};
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
}
}
}
fn main() {
let mut fut = pin!(CountDown(2));
let mut cx = Context::from_waker(Waker::noop());
for i in 1..=3 {
println!("poll {i}: {:?}", fut.as_mut().poll(&mut cx));
}
}The output is:
poll 1: Pending
poll 2: Pending
poll 3: Ready("done")Each call to poll makes one step of progress and then returns. The caller decides when to poll again. The fut.as_mut() call reborrows the pinned future so that fut is still usable on the next loop iteration. A later chapter covers it.
The Context holds a Waker. Here the waker is a no-op, so calling wake_by_ref does nothing. A real executor supplies a waker that schedules another poll.
What each result promises
The contract is easy to break. Two rules apply to the future, and one applies to the caller.
Returning Pending is a promise to wake. Before a future returns Pending, it must arrange for the waker in cx to be called when progress is possible. It might store the waker for an I/O reactor, a timer thread, or another task to call later. If it does not, no one will poll it again, and the task hangs forever with no error. CountDown wakes itself immediately, which is legal but wasteful. It is a busy loop dressed up as async.
poll must return quickly. It runs on the executor's thread. A poll that sleeps, waits on a blocking lock, or runs a long computation stops every other task on that thread. Do a bounded amount of work and return.
Polling after Ready is the caller's mistake. Once a future has returned Ready, the trait does not say what a further poll does. It may panic, return Pending forever, or return a value again. It must not cause undefined behavior in safe code. Async fn futures usually panic with a message such as "async fn resumed after completion". Executors avoid the problem by dropping a future as soon as it is ready.
Spurious polls
An executor may poll a future when nothing has changed. It might poll it before any wake, or twice after one wake. Every poll implementation must therefore check its real state each time. It must not assume that being polled means progress is possible. If the check fails, it returns Pending again and keeps a waker registered.
The waker can also differ between polls. A task may move between executor threads, so the Context may carry a new waker. A future that stores a waker should replace it with the latest one. The method Waker::will_wake lets you skip the replacement when the stored waker is already equivalent.
Working with Poll values
Poll has a few helpers, so you do not need to match by hand every time:
| Helper | Meaning |
|---|---|
| `is_ready()` / `is_pending()` | Boolean test for the variant. |
| `map(f)` | Applies `f` to the value inside `Ready` and leaves `Pending` unchanged. |
| `std::task::ready!(expr)` | Evaluates `expr`. If it is `Pending`, returns `Pending` from the enclosing function. If it is `Ready(v)`, evaluates to `v`. |
The ready! macro is the usual way to forward a Pending from an inner future. This wrapper polls an inner future and doubles its result:
use std::future::{ready, Future};
use std::pin::Pin;
use std::task::{ready, Context, Poll, Waker};
struct Double<F> {
inner: F,
}
impl<F: Future<Output = u32> + Unpin> Future for Double<F> {
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
let v = ready!(Pin::new(&mut self.inner).poll(cx));
Poll::Ready(v * 2)
}
}
fn main() {
let mut fut = Double { inner: ready(21u32) };
let mut cx = Context::from_waker(Waker::noop());
println!("{:?}", Pin::new(&mut fut).poll(&mut cx));
}This prints Ready(42). Two details are worth noting:
- If the inner future returns
Pending,ready!returnsPendingimmediately. The inner future already holdscx's waker, soDoubledoes not need to register anything itself. Pin::newis only available because the inner future isUnpin. That bound appears on theimplfor this reason. Chapters onPinandUnpinexplain it fully.
Double is a small version of what combinators do. A combinator is a future that wraps other futures and forwards poll to them.
Common mistakes
- Returning
Pendingwithout arranging a wake. The task hangs. - Looping inside
polluntil the value arrives. This blocks the thread. ReturnPendingand let the executor schedule other work. - Polling again after
Ready. Drop the future or wrap it in something likefutures::future::Fuseif you need safe repeated polling. - Treating
Pendingas final. It means "not yet". The only final answer isReady. - Assuming one wake means one poll. Handle spurious polls by rechecking state.
Exercise
A hand-written future returns Poll::Pending on its first poll without touching cx.waker(), and the executor does not poll it on any other schedule. What happens to the task, and what is the smallest change that fixes it while keeping the future correct?
Show answer
The task never runs again, because nothing calls the waker and the executor has no other reason to poll it. It hangs silently. The smallest fix is to call cx.waker().wake_by_ref() before returning Pending, as CountDown does. That is correct but busy-loops. A better fix is to store a clone of cx.waker() and have the real event source call wake() when the future can make progress.
Exercise
Why does Double call ready! on the inner poll instead of .unwrap()-style extraction, and what does ready! return when the inner future is Pending?
Show answer
A Poll is not guaranteed to hold a value, so there is nothing to unwrap. ready! returns the value on Ready(v). On Pending it returns Poll::Pending from the enclosing poll, which passes the "not yet" answer to the caller. The inner future has already stored the waker, so the wake still reaches the executor.