Sub topic 2
The Future trait and Poll
This chapter assumes you know Rust ownership and borrowing, traits and generics, closures, and Result with the ? operator. You do not need to have written async code before. By the end you will know what a future is, what poll does, and what the common mistakes look like.
What a future is
A future is a value that represents a computation that may not have finished yet. When you ask it for its result, it either gives you the result or says "not yet". Rust defines this in the standard library:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}There are three parts to read here.
Outputis the type the future produces when it finishes.pollis the only required method. It makes as much progress as it can without blocking, then returns.Pollis the answerpollgives back.
pub enum Poll<T> {
Ready(T),
Pending,
}Poll::Ready(value) means the future is done and here is its output. Poll::Pending means the future cannot finish yet. It has arranged to be told when to try again.
Polling is a question, not a wait
Calling poll never blocks the thread. It returns right away with one of the two variants. The code that calls poll repeatedly is called an executor. A future does nothing on its own. It only moves forward when an executor polls it.
The flow looks like this:
When a future returns Pending, it must first store the waker found in cx (the Context). Later, when the thing it was waiting for is ready, such as a timer firing or data arriving, something calls wake on that waker. The executor then polls the future again. Wakers get their own chapter. For now, treat Context as the way a future says "call me back".
A hand-written future
You rarely implement Future by hand, but doing it once makes the model concrete. This future returns Pending the first time and Ready the second time.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct YieldOnce {
yielded: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}On the first poll, yielded is false. The future sets it to true, asks to be woken, and returns Pending. The call to wake_by_ref tells the executor to poll again immediately. On the second poll, the future returns Ready(()).
You can await it inside an async function. This version is complete and runs with Tokio:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct YieldOnce {
yielded: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
println!("before");
YieldOnce { yielded: false }.await;
println!("after");
}Add tokio = { version = "1", features = ["full"] } to Cargo.toml. The output is before then after. Between them, the task gave control back to the executor once, so other tasks could run.
The contract of poll
A correct poll follows these rules.
- It must not block. A long computation or a blocking system call inside
pollstalls the executor thread. - If it returns
Pending, it must have arranged for the waker to be called later. If it does not, nobody will poll it again, and the task hangs forever. - It should store the most recent waker. The executor may move the task between polls, so the waker from an earlier poll can be out of date.
- After it returns
Ready, polling it again is allowed to panic or misbehave. Executors do not poll a finished future.
The second rule is the source of most hand-written future bugs. The compiler cannot check it.
Why `Pin<&mut Self>`
The receiver is Pin<&mut Self> rather than &mut self. Pinning promises that the future will not be moved in memory while it is being polled. This matters because futures made from async code can hold references to their own fields. Moving such a future would leave those references pointing at the old location. For YieldOnce, the type is Unpin, so self.yielded = true works through the Pin as if it were a plain &mut. The Pin chapter covers the rest.
Composing futures
Futures can wrap other futures. A future that waits for two things can hold both and poll each in turn. Here is a simplified wrapper that adds one to the output of an inner future:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct AddOne<F> {
inner: F,
}
impl<F> Future for AddOne<F>
where
F: Future<Output = u32> + Unpin,
{
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
match Pin::new(&mut self.inner).poll(cx) {
Poll::Ready(n) => Poll::Ready(n + 1),
Poll::Pending => Poll::Pending,
}
}
}The wrapper passes the same cx down. If the inner future returns Pending, the wrapper returns Pending, and the inner future has already registered the waker. This is how async code nests: every .await is a poll of an inner future, and a Pending propagates up to the executor.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning `Pending` without registering or calling the waker | The task never finishes and nothing is printed or returned | Call `cx.waker().wake_by_ref()` or store the waker for later |
| Calling `wake_by_ref` on every `Pending` with no real progress | The executor spins at 100% CPU | Wake only when the awaited event has happened |
| Blocking inside `poll` | Other tasks on the same thread stop running | Move blocking work to `spawn_blocking` |
| Polling a future again after `Ready` | Panic, or a wrong result | Track completion, or use a fused future |
| Creating a future and never awaiting it | The work never runs | Await it, or hand it to an executor |
The last row is covered in the chapter on laziness.
Summary of the model
- A future is an object with a
pollmethod. pollreturnsReady(output)orPendingand never blocks.- A future that returns
Pendingis responsible for getting its waker called later. - An executor owns the polling loop. Without one, a future is inert.
asynccode is built from these pieces. The next chapters show howasync fnproduces futures for you.
Exercise
A future's poll returns Poll::Pending but never uses the waker in cx. The executor has no other work to do. What happens to that task, and why?
Show answer
The task hangs and never completes. The executor only polls a task again after its waker is called. Since the future did not register or call the waker, nothing signals that progress is possible, so the executor never polls it again.
Exercise
Modify YieldOnce so that it returns Pending three times before returning Ready. What field do you need, and what must each Pending path still do?
Show answer
Replace the yielded: bool field with a counter such as remaining: u32, starting at 3. In poll, if remaining == 0 return Poll::Ready(()). Otherwise decrement it, call cx.waker().wake_by_ref(), and return Poll::Pending. Every Pending path must still arrange a wakeup, here by waking immediately.