Sub topic 1
Futures do nothing until polled
Prerequisites
This chapter assumes you know basic Rust (ownership, traits, Drop) and the async/await syntax. It also assumes you have used #[tokio::main] and tokio::spawn. Later chapters build on the idea here: cancelling a future means dropping it, and that only makes sense once you know a future does nothing until something polls it.
Creating a future runs no code
Calling an async fn does not run its body. It returns a value that implements the Future trait. That value holds the function's arguments and its current position, like a paused state machine.
async fn greet() {
println!("greet ran");
}
#[tokio::main]
async fn main() {
let fut = greet();
println!("created the future");
fut.await;
println!("awaited it");
}The output is created the future, then greet ran, then awaited it. The body of greet only starts when .await drives the future.
If you drop the future without awaiting it, the body never runs. The compiler warns about this because Future is marked #[must_use].
async fn greet() {
println!("greet ran");
}
#[tokio::main]
async fn main() {
let fut = greet();
drop(fut);
println!("nothing was printed by greet");
}What polling is
The Future trait has one method:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>Poll is an enum with two variants: Poll::Ready(value) when the future has finished, and Poll::Pending when it cannot make progress yet. The Context carries a Waker. A future that returns Pending must arrange for the waker to be called when it can try again. The runtime does not busy-loop. It sleeps until a waker fires.
You can see this with std::future::poll_fn, which builds a future from a closure. This one returns Pending twice, asking to be woken each time, then finishes.
use std::future::poll_fn;
use std::task::Poll;
#[tokio::main]
async fn main() {
let mut polls = 0;
poll_fn(|cx| {
polls += 1;
if polls < 3 {
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Ready(())
}
})
.await;
println!("polled {polls} times");
}The output is polled 3 times. Calling wake_by_ref before returning Pending tells the runtime to poll again straight away. If the closure returned Pending without arranging a wake-up, the task would hang forever.
Why this matters for cancellation
An .await on a future polls it repeatedly until it is ready. Between two polls, the future is only data sitting in memory. Nothing is running on its behalf. That has two consequences:
- A future can only stop at the points where it returned
Pending. Between those points its code runs without interruption. - Dropping a future that has not finished stops it for good. No thread is killed and no signal is sent. The runtime simply stops polling, and the future's locals are dropped.
tokio::spawn is the exception to "nothing happens until awaited". It hands the future to the runtime, which polls it in the background even if you never await the JoinHandle. The future is still lazy until that moment of spawning.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Calling an `async fn` and ignoring the result | The body never runs | Add `.await` or `tokio::spawn` |
| Returning `Pending` without registering the waker | The task hangs | Store the waker or call `wake_by_ref` |
| Assuming a created future has already started | Timing and ordering bugs, for example a timer that starts late | Remember the clock starts at first poll |
Exercise
A function creates let fut = fetch_data(); where fetch_data is an async fn that prints a log line first. The code then does heavy synchronous work for two seconds and finally calls fut.await. When does the log line print, and why?
Show answer
It prints after the two seconds of synchronous work, when fut.await first polls the future. Calling fetch_data() only builds the future and runs none of its body.