Sub topic 4
Futures do nothing until polled
This chapter assumes you know Rust ownership and borrowing, traits, closures with move, and how to add Tokio to a Cargo project. It also assumes you have seen async fn and .await. Here you will learn why a future does no work until something polls it, and the mistakes that follow from that.
Creating a future is not running it
Calling an async fn, or writing an async block, builds a value. That value implements Future. None of the body runs at that point. The body runs only when an executor calls poll on the future, and .await does that for you.
#[tokio::main]
async fn main() {
let fut = async {
println!("running");
};
println!("created");
fut.await;
}The output is created, then running. The println!("running") line does not execute when fut is built. It executes during fut.await.
Why Rust works this way
Rust futures are state machines that sit inert until polled. Nothing is scheduled in the background when you create one. This differs from some other languages, where a promise starts running as soon as you create it.
Lazy futures have practical benefits:
- A future that is never awaited costs no CPU time and does no I/O.
- You can build a future first and decide later how to run it: await it, spawn it, or combine it with
join!. - Dropping a future before it finishes stops it. Chapter on cancellation covers this in detail.
The flow of a poll
A common mistake: the unused future
Because a future does nothing alone, forgetting .await silently skips the work.
use std::time::Duration;
use tokio::time::sleep;
async fn save() {
sleep(Duration::from_millis(100)).await;
println!("saved");
}
#[tokio::main]
async fn main() {
save(); // Bug: the future is created and dropped. Nothing is printed.
println!("done");
}The compiler warns with unused implementer of Future that must be used. Treat this warning as an error. The fix is save().await.
Work is not done when you build the futures
The same laziness applies when you collect futures in a list. Building a Vec of futures starts nothing. Each one begins only when it is awaited, spawned, or passed to a combinator.
By contrast, tokio::spawn is the exception. It hands the future to the runtime, which begins polling it right away on a worker thread, even if you never await the JoinHandle.
| Action | Does the body start? |
|---|---|
| Call an `async fn` | No |
| Write an `async { }` block | No |
| Use `.await` on it | Yes, runs to completion |
| Pass it to `tokio::spawn` | Yes, as an independent task |
| Drop it unpolled | Never runs |
Exercise
This program prints only "done". Why does fetch never print, and what is the smallest change that makes it print before "done"?
async fn fetch() { println!("fetched"); }
#[tokio::main]
async fn main() {
fetch();
println!("done");
}
Show answer
Calling fetch() only creates a future, which is dropped without being polled, so its body never runs. Adding .await (fetch().await;) makes the runtime poll it, and "fetched" prints before "done".