Sub topic 2
Await points are where a task can stop
This chapter assumes you know basic Rust, including ownership and the Drop trait. It also assumes you know async/await syntax and how to use #[tokio::main] and tokio::spawn. The previous chapter showed that a future does nothing until something polls it. This chapter covers the other half: once a future is running, where can it be stopped?
The rule
A task can only be stopped at an .await that returns Pending. Between two await points, your code runs as ordinary synchronous Rust. Nothing can interrupt it. The runtime has no way to pause a task in the middle of a loop or a function call.
This follows from how futures work. Tokio calls poll on the task's future. The future runs until it finishes or until some inner future returns Poll::Pending. At that moment control goes back to the runtime, which can then do other work. That includes dropping the future, which is how cancellation happens (covered in the next chapter).
Which awaits can stop a task
An .await is a point where the task may stop. It does not always stop. If the awaited future is already ready, the task continues without giving up control.
use std::time::Duration;
use tokio::time::sleep;
async fn step_one() -> u32 {
println!("step one");
1
}
#[tokio::main]
async fn main() {
let a = step_one().await; // ready at once, no suspension
println!("a = {a}");
sleep(Duration::from_millis(10)).await; // returns Pending first
println!("after sleep");
}step_one().await completes inside a single poll. sleep(...).await returns Pending until the timer fires, so it is a real suspension point.
What this means for code you write
Everything between two suspension points is atomic from the point of view of cancellation. Consider this function:
use std::time::Duration;
use tokio::time::sleep;
async fn update(counter: &mut u32, log: &mut Vec<String>) {
*counter += 1;
sleep(Duration::from_millis(10)).await;
log.push(format!("counter is {counter}"));
}If the future is dropped while it waits on sleep, the increment has already happened but the log line never will. The two updates are separated by an await point, so a cancel can fall between them. If you need both to happen or neither, put them on the same side of an await. You can also design the code so that a half-finished state is safe.
The reverse also holds. Code with no await points cannot be cancelled at all:
use std::time::Duration;
use tokio::time::timeout;
async fn busy() -> u64 {
let mut total = 0u64;
for i in 0..2_000_000_000u64 {
total = total.wrapping_add(i);
}
total
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(10), busy()).await;
println!("timed out: {}", result.is_err());
}This runs the whole loop before timeout gets a chance to check the clock, because busy never yields. The timeout fires only after the loop ends. A later chapter on blocking code returns to this. For now, remember that a timeout is only as precise as the gaps between your await points.
Common mistakes
- Assuming a deadline interrupts running code. It does not. It takes effect at the next point where the future returns
Pending. - Treating
.awaitas always suspending. A ready future continues without a break, so a loop of ready awaits can also starve other tasks. - Writing multi-step updates with an await in the middle and expecting them to be all-or-nothing.
Exercise
A function sets state.ready = false, awaits a network call, then sets state.ready = true. The caller wraps it in a timeout that fires during the network call. What is the value of state.ready afterwards, and why?
Show answer
It stays false. The timeout drops the future at the network await, which is a suspension point. The code after the await never runs, so ready is never set back to true. Fixes include using a drop guard to restore the value, or restructuring so the state is not left half-updated across an await.