Sub topic 16
What the compiler generates for async fn
This chapter assumes you know how Future and Poll work, what .await does, and the basics of Pin. Here you will see what the compiler builds from an async fn, and why that explains several behaviors you have already met.
An async fn becomes a state machine
An async fn does not run when you call it. It returns a value whose type the compiler generates. That type implements Future, and its poll method contains your function body, split at each .await.
Each .await is a point where the future may return Poll::Pending. The compiler turns every such point into a state. The generated type is an enum-like struct that records:
- which state it is in (not started, suspended at the first
.await, suspended at the second, finished); - the local variables that are still needed after each suspension point.
When the executor polls the future, poll jumps to the saved state, runs until the next .await that returns Pending, saves its variables, and returns. When the awaited future is ready, the next poll continues from that state.
A hand-written equivalent
The function below awaits twice.
use std::time::Duration;
use tokio::time::sleep;
async fn steps() -> u32 {
let a = 1;
sleep(Duration::from_millis(10)).await;
let b = a + 1;
sleep(Duration::from_millis(10)).await;
b + 1
}
#[tokio::main]
async fn main() {
println!("{}", steps().await);
}Conceptually, the compiler produces something like this enum. This is a simplified model, not real compiler output.
enum StepsState {
Start,
WaitingFirst { a: u32 },
WaitingSecond { b: u32 },
Done,
}Only a is stored in the first waiting state, and only b in the second. Variables that are not used after a suspension point are not kept.
Consequences you can observe
The state machine explains behaviors from earlier chapters.
- Laziness. Calling
steps()only creates the value in itsStartstate. Nothing runs until the first poll. - Pinning. A local variable can hold a reference to another local variable across an
.await. The generated type then contains a reference into itself. Moving it would break that reference, which is why futures must be pinned before polling. - Size. The future is a single value that holds all saved variables. Its size is roughly that of the largest set of data alive across one suspension point, plus the state tag.
- Cancellation. Dropping the future drops whatever the current state holds. No code after the suspended
.awaitruns.
Recursion and size
Because the future's size must be known, an async fn cannot call itself directly. The type would contain itself. Boxing the recursive call breaks the cycle.
use std::future::Future;
use std::pin::Pin;
fn countdown(n: u32) -> Pin<Box<dyn Future<Output = u32>>> {
Box::pin(async move {
if n == 0 {
0
} else {
countdown(n - 1).await + 1
}
})
}
#[tokio::main]
async fn main() {
println!("{}", countdown(3).await);
}Exercise
A local String is created in an async fn and last used before the first .await. Is it stored in the generated state machine?
Show answer
No. Only variables that are still needed after a suspension point are saved in the state. A value that is finished before the first .await stays in the ordinary stack frame of poll and is gone when poll returns.
Exercise
Why does a directly recursive async fn fail to compile, and how do you fix it?
Show answer
The generated future type would contain itself, so its size would be infinite. Return a boxed future, such as Pin<Box<dyn Future<Output = T>>>, so the recursive call sits behind a pointer of fixed size.