Sub topic 5
Futures do nothing until polled
Prerequisites
This chapter assumes you know the Future trait and Poll, and that you can write async fn and .await. It also assumes you can run a program with Tokio (add tokio with the "full" feature in Cargo.toml).
The rule
Calling an async fn or writing an async block does not run any of its body. It builds a value that implements Future. The body runs only when something polls that value, and the first poll starts it from the top.
#[tokio::main]
async fn main() {
let fut = async {
println!("running");
};
println!("created");
fut.await;
}The output is created, then running. Between the two lines, fut is just a value sitting on the stack.
This differs from languages such as JavaScript, where calling an async function starts it immediately. In Rust, the caller decides when the work begins.
What the call actually does
When you call async fn record(), the compiler-generated code moves the arguments into a struct and returns it. That struct is the future. It starts in an "unstarted" state and holds the arguments the body will need. Nothing else happens.
A global counter makes this visible:
use std::sync::atomic::{AtomicUsize, Ordering};
static CALLS: AtomicUsize = AtomicUsize::new(0);
async fn record() {
CALLS.fetch_add(1, Ordering::SeqCst);
}
#[tokio::main]
async fn main() {
let fut = record();
println!("after call: {}", CALLS.load(Ordering::SeqCst));
fut.await;
println!("after await: {}", CALLS.load(Ordering::SeqCst));
}This prints after call: 0 and then after await: 1.
Arguments are evaluated at the call, not at the first poll. In greet(&make_name()), make_name() runs when you call greet. Only the body of greet waits.
Who polls
Something has to call poll. There are two sources:
.awaitinside another future polls the inner future each time the outer future is polled. If the inner future returnsPending, the outer one returnsPendingtoo.- The runtime polls the outermost future. With
#[tokio::main], that is the body ofmain.
You can see the mechanism without a runtime by polling by hand. This needs Rust 1.85 or later for Waker::noop.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
async fn hello() -> u32 {
println!("body runs");
42
}
fn main() {
let fut = hello();
println!("created");
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
match fut.as_mut().poll(&mut cx) {
Poll::Ready(v) => println!("ready: {v}"),
Poll::Pending => println!("pending"),
}
}The output is created, body runs, ready: 42. The body has no real waiting point, so one poll finishes it.
Common errors
Forgetting `.await`
async fn save() {
println!("saved");
}
#[tokio::main]
async fn main() {
save();
println!("done");
}This program prints only done. The future from save() is created and immediately dropped, and its body never runs. The compiler warns with "unused implementer of Future that must be used". Treat that warning as an error in async code.
A related mistake is let _ = save();. The let _ binding silences the warning, but the future is still dropped without running.
Collecting futures and never driving them
Pushing futures into a Vec does not start them. They run only when something awaits or polls them, for example futures::future::join_all, or a for loop that awaits each one. Awaiting in a loop runs them one after another. Starting them together is covered in the chapter on join! and select!.
Expecting the clock to start at the first poll
Lazy does not mean every part of a future is deferred. tokio::time::sleep(d) computes its deadline when you create it, not when you first poll it. In this example, the sleep may already be partly or fully elapsed when it is awaited:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let s = sleep(Duration::from_millis(200));
std::thread::sleep(Duration::from_millis(250));
s.await;
println!("returned immediately");
}The std::thread::sleep call blocks the thread, which is itself a mistake in async code, but here it only demonstrates the deadline. When s.await runs, the deadline has passed, so it completes on the first poll.
Lazy versus eager
| Construct | When work begins |
|---|---|
| Call to an `async fn` | On the first poll |
| `async { ... }` block | On the first poll |
| `tokio::spawn(fut)` | Soon after the call, on the runtime, even if you never await the handle |
| `std::thread::spawn` | Immediately on a new OS thread |
| `tokio::join!(a, b)` | When the enclosing async code reaches the macro, which then polls both |
tokio::spawn is the main exception. It hands the future to the runtime, and the runtime becomes its poller. You do not need to await the returned JoinHandle for the task to run. You only need it if you want the output or the error.
Practical consequences
- Build a future in one place and run it in another. Returning
impl Futurefrom a function does not start the work. - Retrying is easy: call the
async fnagain to get a fresh, unstarted future. - Do not rely on side effects at call time. Put them in the body, and remember they happen only after a poll.
- Keep borrowed data alive until the future is finished. The future stores the references you passed, so the borrow checker ties its lifetime to them.
Exercise
The program below prints only "start" and "end". Explain why "work" never appears, and give the one-line fix. async fn work() { println!("work"); } #[tokio::main] async fn main() { println!("start"); let _job = work(); println!("end"); }
Show answer
Calling work() only creates a future. Nothing polls it, and it is dropped at the end of main without ever running its body. The _job binding also suppresses the unused-future warning. The fix is to await it: work().await;, or _job.await; before the final print. Awaiting makes the runtime poll it, so "work" prints between "start" and "end".