Sub topic 5
Async code as a state machine
This chapter assumes you know ownership and borrowing, enums and pattern matching, and how to write and .await a simple async fn. It also assumes you have seen the Future trait and Poll::Ready and Poll::Pending. Here you will see what the compiler builds from an async fn.
From async fn to an enum
An async fn body can pause at every .await and continue later. Rust cannot keep a call stack for each paused function, so the compiler turns the body into an enum. Each variant is one state the function can be paused in. The generated type implements Future, and each call to poll runs the body from the current state until it either finishes or reaches an .await that returns Pending.
Consider this function:
async fn add(a: u32, b: u32) -> u32 {
a + b
}
async fn run() -> u32 {
let x = add(1, 2).await;
x * 2
}Calling run() runs none of its body. It returns a value of the generated type, which starts in its first state.
The states
For run, the compiler produces something like this. The real type is hidden and cannot be named, so this is a model.
enum RunState {
Start,
AwaitingAdd { fut: AddFuture },
Done,
}- Start: the function has not run yet.
- AwaitingAdd: the function is suspended at
add(1, 2).await. It stores the inner future, becausepollmust be able to poll it again. - Done: the future returned
Readyand must not be polled again.
On each poll, the generated code matches on the current state. In AwaitingAdd it polls the inner future. If that returns Pending, the outer poll returns Pending too, and the state stays the same. If it returns Ready(x), the code computes x * 2, moves to Done, and returns Ready.
What gets stored across a suspension
Only values that are alive across an .await become fields of a variant. A local variable that is used and dropped before the next .await costs no space in the future. This matters in two ways:
- Size. The future is as large as its largest variant, plus a tag. Holding a big array across an
.awaitmakes every future that awaits you bigger. - Borrows. A reference to a local that lives across an
.awaitis stored inside the future, pointing at another field of the same future. This is a self-reference, and the next chapters show why it forcesPin.
async fn read_len() -> usize {
let buf = [0u8; 1024];
let view = &buf[..];
tokio_like_yield().await;
view.len()
}
async fn tokio_like_yield() {}Here buf and view are both used after the .await, so both are stored in the future, and view points into buf.
Why this design
Because the state lives in an ordinary value, an async task needs no separate stack. It costs one allocation at most, and often none. The price is that futures can be self-referential, so they cannot be moved freely once polled.
Exercise
In an async fn, a local String is created, used, and dropped before the first .await. Is it stored in the generated future? What if it is used after the .await?
Show answer
Not stored in the first case, because it is not alive at the suspension point. In the second case it is stored as a field of the state variant for that .await, so it adds to the size of the future.