Sub topic 17
What the compiler generates for async fn
This chapter assumes you know Future, Poll, Pin, and the .await keyword from the earlier chapters. You should also be comfortable with enums and match. Here you will see what async fn turns into: an anonymous type that implements Future.
An async fn is a constructor for a state machine
Calling an async fn runs none of its body. It returns a value of an anonymous type, and that type implements Future. The compiler builds the type from the function body.
The compiler splits the body at each .await. Each split point becomes a state in an enum-like type. Every state stores the local variables that are still needed after that point. poll jumps to the current state, runs code until the next .await that returns Pending, saves its locals, and returns Pending. When the body finishes, poll returns Ready(value).
The real compiler also has a "Panicked" state. Polling a future again after it returned Ready panics, which matches the Returned state above.
Writing the state machine by hand
Take this async function:
async fn add_after_yield(a: u32, b: u32) -> u32 {
tokio::task::yield_now().await;
a + b
}The version below does the same job by hand. It reuses the YieldOnce future from the earlier chapter on Future and Poll. The enum has one variant per state. The Waiting variant keeps a, b, and the inner future, because all three are needed after the suspension.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct YieldOnce {
yielded: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
enum AddAfterYield {
Start { a: u32, b: u32 },
Waiting { a: u32, b: u32, inner: YieldOnce },
Done,
}
impl Future for AddAfterYield {
type Output = u32;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
// Every field is Unpin, so the whole enum is Unpin and get_mut is allowed.
let this = self.get_mut();
loop {
match &mut *this {
AddAfterYield::Start { a, b } => {
let (a, b) = (*a, *b);
*this = AddAfterYield::Waiting {
a,
b,
inner: YieldOnce { yielded: false },
};
}
AddAfterYield::Waiting { a, b, inner } => match Pin::new(inner).poll(cx) {
Poll::Ready(()) => {
let sum = *a + *b;
*this = AddAfterYield::Done;
return Poll::Ready(sum);
}
Poll::Pending => return Poll::Pending,
},
AddAfterYield::Done => panic!("polled after completion"),
}
}
}
}
#[tokio::main]
async fn main() {
let sum = AddAfterYield::Start { a: 2, b: 3 }.await;
println!("{sum}");
}This prints 5. Three details matter:
- The
Startarm does not return. It moves toWaitingand loops, so the samepollcall goes on to poll the inner future. - On
Pending,pollreturns without changing state. The nextpollresumes in the same arm. This is how the future "remembers" where it was. - The
Donearm panics, which mirrors what compiler-generated futures do.
The real generated type is more complex because it must also handle borrows that point into the future itself. That is why it needs Pin, as the next section explains.
Why self-references need Pin
Consider a body that borrows a local across an .await:
async fn read_it() {
let buf = [0u8; 16];
let slice = &buf[..];
tokio::task::yield_now().await;
println!("{}", slice.len());
}Both buf and slice must be stored in the future, because both are used after the .await. slice points at buf, which lives in the same struct. That makes the future self-referential. If the future were moved to a new address, slice would still point at the old address. Hand-written Rust cannot express this safely, but the compiler generates it. The generated type is !Unpin, and Pin guarantees that a pinned future is never moved. This is the link between pinning and state machines.
What gets stored
Only values that are live across an .await go into the generated type. This has a direct effect on the future's size, which you can check:
use std::mem::size_of_val;
use tokio::task::yield_now;
async fn holds_buffer() {
let buf = [0u8; 1024];
yield_now().await;
println!("{}", buf.len());
}
async fn drops_buffer() {
{
let buf = [0u8; 1024];
println!("{}", buf.len());
}
yield_now().await;
}
#[tokio::main]
async fn main() {
println!("{}", size_of_val(&holds_buffer()) >= 1024);
println!("{}", size_of_val(&drops_buffer()) < 1024);
}This prints true twice. The first future must store buf because it is used after the suspension point. The second future never needs buf after the .await, so it does not store it.
| Value | Stored in the future? |
|---|---|
| Function arguments | Yes, from creation until the body is done with them |
| Locals used after an `.await` | Yes |
| Locals that go out of scope before the next `.await` | No |
| Awaited inner futures | Yes, while they are being awaited |
Consequences you will meet
Futures can be large. Big arrays or structs held across an .await make every future that awaits yours larger too. Spawned tasks are allocated on the heap at their full size. Shrink them by dropping big values in an inner block before awaiting, or by boxing them.
Send is decided by what lives across an .await. A future is Send only if every value stored in it is Send. A non-Send value that is dropped before the .await is not stored, so it does not matter. This code compiles with tokio::spawn because the Rc is dropped inside the inner block:
use std::rc::Rc;
#[tokio::main]
async fn main() {
tokio::spawn(async {
{
let rc = Rc::new(5);
println!("{rc}");
}
tokio::task::yield_now().await;
})
.await
.unwrap();
}If you remove the inner braces, rc is live across the .await. The compiler then reports that the future cannot be sent between threads safely, and it names the variable. Holding a std::sync::MutexGuard across an .await fails the same way.
Recursion needs indirection. A future that awaits itself would contain itself, so its size would be infinite. Boxing the recursive call gives it a fixed size:
async fn countdown(n: u32) -> u32 {
if n == 0 {
0
} else {
Box::pin(countdown(n - 1)).await + 1
}
}
#[tokio::main]
async fn main() {
println!("{}", countdown(3).await);
}This prints 3. Recursive async fn with Box::pin at the call site works on Rust 1.77 and later.
Dropping a future drops its state. Dropping a suspended future drops every local stored at that point. That is the mechanism behind cancellation by dropping, from the cancellation chapter. Code after the suspended .await never runs.
Exercise
A task spawned with tokio::spawn fails to compile with the error "future cannot be sent between threads safely", and the note points at a variable of type Rc<String>. The variable is created, used, and last used before the first .await. What is the likely cause, and how do you fix it?
Show answer
The compiler decides what is stored in the future from scopes, not from last use. The Rc is still in scope at the .await, so it counts as live across it, and Rc is not Send. Fix it by ending its scope before the .await, either with an inner block or with an explicit drop(rc) call before the .await. You can also switch to Arc if the value really must live across the .await.
Exercise
Why does the hand-written AddAfterYield future not need Pin tricks, while the generated future for read_it does?
Show answer
AddAfterYield contains only u32 values and a YieldOnce, which are all Unpin, so moving it is harmless and getmut is allowed. The future generated for readit stores a reference that points to another field of the same future. Moving it would leave that reference dangling, so the future is !Unpin and must be pinned before it is polled.