Sub topic 7
Writing a Future by hand
This chapter assumes you know the Future trait, Poll, and what a Waker is for. You will implement a future yourself and see how the poll contract works.
What a hand-written future must do
A future is a type with a poll method. Each call must return one of two values:
Poll::Ready(value)means the work is finished.Poll::Pendingmeans the work is not finished. Before returning it, the future must arrange for the waker in theContextto be woken later. If it doesn't, the executor has no reason to poll it again, and the task can hang forever.
A countdown future
CountDown returns Pending a fixed number of times and then finishes. It wakes itself each time so that the executor polls it again.
use std::future::Future;
use std::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 = CountDown(3);
let mut cx = Context::from_waker(Waker::noop());
let mut polls = 0;
loop {
polls += 1;
match Pin::new(&mut fut).poll(&mut cx) {
Poll::Ready(v) => {
println!("{v} after {polls} polls");
break;
}
Poll::Pending => println!("pending"),
}
}
}This prints pending three times, then done after 4 polls. The main function is a stand-in for an executor. It polls in a loop and uses a waker that does nothing, which is fine here because the loop polls again without waiting. Waker::noop() needs Rust 1.85 or later. A later chapter builds a real block_on.
Details worth noting
- The signature.
polltakesself: Pin<&mut Self>, not&mut self.CountDowncontains only au32, so it isUnpin. That is whyself.0 -= 1compiles:Pin<&mut Self>gives mutable access throughDerefMutonly whenSelf: Unpin. It is also whyPin::new(&mut fut)works inmain. - The state lives in the struct. The counter is the future's state, and each
polladvances it. This is a small version of the state machine the compiler generates for anasync fn. - Waking before returning. The call to
wake_by_refhappens beforePendingis returned. A real future would instead store the waker and call it when an event occurs, such as a socket becoming readable or a timer firing.
Common mistakes
- Doing blocking work inside
poll. This stalls the executor thread. - Storing a waker once and never updating it. The executor may pass a different waker on a later poll, so replace the stored one if
will_wakesays they differ. - Forgetting the
Unpinrequirement and trying to mutate fields of a!Unpintype throughPin<&mut Self>withoutunsafe.
Exercise
Suppose CountDown::poll returned Poll::Pending without calling cx.waker().wake_by_ref(). The executor polls it once and gets Pending. What happens next, and why?
Show answer
The executor never polls the future again, so the task hangs. An executor re-polls a pending future only after its waker is woken. Nothing calls the waker, so the executor has no signal that the future can make progress.