Sub topic 5
Async code as a state machine
This chapter assumes you know what Future and Poll are, and that you have written simple async fn code. It also assumes you can read enums and match. Here you will see what the compiler builds from an async fn, and you will write that structure by hand.
From one function to one enum
An async fn looks like a function that pauses. A function that pauses needs somewhere to keep its local variables while it is paused. The call stack cannot hold them, because poll returns to the executor every time the future is Pending.
The compiler solves this by turning the body into an anonymous struct that implements Future. That struct behaves like an enum with one variant per state:
- An initial state that holds the arguments.
- One state for each
.await, holding the future being awaited and every local variable still needed after that point. - A final state for "returned".
- A poisoned state for "panicked".
Each call to poll resumes the body at the current state. It runs until the next .await returns Pending, or until the body finishes. Resuming means jumping to the code after the last suspension point, with the saved locals available again.
You never see this type. You only see impl Future<Output = T>.
A hand-written equivalent
Start with a future that is Pending once and Ready the second time:
use std::future::Future;
use std::pin::{pin, Pin};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
async fn sum(x: u32) -> u32 {
let a = x * 2;
YieldOnce(false).await;
let b = a + 1;
YieldOnce(false).await;
a + b
}
enum Sum {
Start { x: u32 },
WaitFirst { a: u32, y: YieldOnce },
WaitSecond { a: u32, b: u32, y: YieldOnce },
Done,
}
impl Future for Sum {
type Output = u32;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
let this = self.get_mut();
loop {
match &mut *this {
Sum::Start { x } => {
let a = *x * 2;
*this = Sum::WaitFirst { a, y: YieldOnce(false) };
}
Sum::WaitFirst { a, y } => match Pin::new(y).poll(cx) {
Poll::Ready(()) => {
let a = *a;
let b = a + 1;
*this = Sum::WaitSecond { a, b, y: YieldOnce(false) };
}
Poll::Pending => return Poll::Pending,
},
Sum::WaitSecond { a, b, y } => match Pin::new(y).poll(cx) {
Poll::Ready(()) => {
let result = *a + *b;
*this = Sum::Done;
return Poll::Ready(result);
}
Poll::Pending => return Poll::Pending,
},
Sum::Done => panic!("`Sum` polled after completion"),
}
}
}
}
struct Noop;
impl Wake for Noop {
fn wake(self: Arc<Self>) {}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let waker = Waker::from(Arc::new(Noop));
let mut cx = Context::from_waker(&waker);
let mut polls = 0;
loop {
polls += 1;
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
println!("ready after {polls} polls");
return value;
}
}
}
fn main() {
println!("{}", block_on(sum(5)));
println!("{}", block_on(Sum::Start { x: 5 }));
}Both calls print ready after 3 polls and then 21. The compiler's version does the same thing as Sum, with these steps:
- The first
pollcomputesa, moves toWaitFirst, and polls the inner future. That future returnsPending, sopollreturnsPending. - The second
pollfindsWaitFirst, seesReady, computesb, moves toWaitSecond, and returnsPendingagain. - The third
pollfinishes the body and returnsReady(21).
The loop matters. When a state finishes without suspending, the machine moves straight to the next state in the same poll call. It returns only on Pending or Ready.
The states as a diagram
What each state stores
The compiler stores a variable in a state only if it is used after that suspension point. In sum, the state at the first .await holds a, because a is used later, and the pending YieldOnce. It does not hold x, which is dead after a is computed.
| State | Fields kept | Why |
|---|---|---|
| Start | `x` | The argument has not been used yet. |
| WaitFirst | `a`, inner future | `a` is read after the await. |
| WaitSecond | `a`, `b`, inner future | Both are read in the final sum. |
| Done | nothing | The result was moved out. |
The generated future is as large as its largest state, plus a tag that records which state is current. Compiler versions differ in how well they overlap storage between states, so do not rely on exact sizes. Holding a large buffer across an .await makes every future that awaits you larger.
Consequences you will meet
Nothing runs until polled. Calling sum(5) builds the Start state and does no work. This is why async functions are called lazy.
Recursion needs boxing. A recursive async fn would contain a copy of its own state machine, so its size would be infinite. The compiler rejects it, and you break the cycle with Box::pin, which a later chapter covers.
Polling after completion is a bug. The Done arm above panics. The compiler-generated version also panics. The Future contract does not promise any particular behavior after Ready.
Drop depends on the state. If you drop a future in WaitFirst, Rust drops the fields stored for that state and nothing else. Locals from later states were never created. This is the mechanism behind cancellation.
Fields can point at each other. If the body holds a reference to a local across an .await, the saved state holds both the local and a reference to it, inside the same struct. Moving the struct would leave that reference dangling. Our Sum avoids this because it stores only plain values, which is why Pin::new and get_mut worked. The next chapters explain the general case.
Common mistakes
- Expecting
.awaitto block the thread. It returnsPendingup the chain ofpollcalls, and the thread is free to run other tasks. - Forgetting that every
.awaitis a point where the future may be dropped and never resumed. Code after it might never run. - Holding a
MutexGuardor a large value across an.awaitwithout thinking about it. The guard becomes part of the saved state, and that affects both size andSend, as a later chapter shows.
Exercise
A future for async fn f() { let big = [0u8; 4096]; g().await; } is much larger than you expect, even though big is never used after the await. Why might this happen, and how would you reduce the size?
Show answer
In the generated state machine, a local is stored across a suspension point only if it is live after it. Because big is unused afterward, it ideally would not be stored. In practice, the compiler can still keep it in the state if the variable's scope extends over the await, because it is dropped at the end of scope. Dropping it early would make it unnecessary to store. To shrink the future, end its scope before the await by wrapping its use in an inner block, or by calling drop(big) before awaiting. Then it is not live at the suspension point.