Sub topic 3
Polling: Poll::Ready and Poll::Pending
This chapter assumes you know Rust enums and pattern matching, have read the previous chapter on the Future trait, and understand that Pin<&mut Self> means "a mutable reference to a value that will not move". Pinning and wakers get their own chapters, so here they are only used.
The Poll enum
A future does no work until something asks it to make progress. That request is a call to poll, and the answer is a Poll<T>:
pub enum Poll<T> {
Ready(T),
Pending,
}Poll::Ready(value)means the future finished andvalueis its output.Poll::Pendingmeans the future cannot finish yet. It has not failed and it has not been cancelled.
poll never blocks. It does as much work as it can, then returns right away. A future that must wait for a socket, a timer, or another task returns Pending instead of sleeping the thread.
One poll at a time
The caller, usually an executor, drives a future by polling it repeatedly. It stops when it sees Ready.
The following program polls a future by hand. It uses Waker::noop(), which is stable since Rust 1.85, to build a Context. The Context argument is covered in a later chapter. For now, note that a future that returns Pending must arrange to be polled again, which is why this one calls wake_by_ref.
use std::future::Future;
use std::pin::{pin, Pin};
use std::task::{Context, Poll, Waker};
struct ReadyOnSecondPoll {
polled: bool,
}
impl Future for ReadyOnSecondPoll {
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
if self.polled {
Poll::Ready(42)
} else {
self.polled = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
fn main() {
let mut cx = Context::from_waker(Waker::noop());
let mut fut = pin!(ReadyOnSecondPoll { polled: false });
println!("first poll: {:?}", fut.as_mut().poll(&mut cx));
println!("second poll: {:?}", fut.as_mut().poll(&mut cx));
}It prints Pending for the first poll and Ready(42) for the second. Each call goes through as_mut() because poll takes Pin<&mut Self> by value. as_mut() reborrows the pinned reference so you can poll again.
Rules to remember
- Do not poll after
Ready. TheFuturecontract allows a finished future to panic, block, or misbehave if polled again. Executors drop or discard a future once it returnsReady. Pendingis a promise. Returning it means "I have arranged to be woken". If you returnPendingand never arrange a wake-up, the task is never polled again and hangs silently.- Never block inside
poll. A sleeping or blocking call stalls every other future that shares the thread. - Polls can be spurious. A future may be polled when nothing has changed. It must check its state and return
Pendingagain if it is not done.
Poll<T> also has helpers such as is_ready(), is_pending() and map(). The ? operator works on Poll<Result<T, E>>, so it can propagate errors from a Ready(Err(_)).
Exercise
A future's poll is called and returns Poll::Pending. Name two things that must be true for the future to eventually complete, and say what happens if the first is missing.
Show answer
The future must have arranged for its waker to be called (for example by calling cx.waker().wake_by_ref() or storing the waker for an event source), and the executor must poll it again after that wake-up. Without the wake-up, the executor has no reason to poll the future again, so the task hangs forever without an error.