Sub topic 2
Await points are where a task can stop
This chapter assumes you know async/await syntax, have used tokio::spawn and #[tokio::main], and understand that a future is a value you poll. The previous chapter covered why a future does nothing until polled. This one covers where a future can be stopped once it is running.
A poll runs until the next Pending
The compiler turns an async fn into a state machine. Each .await marks a boundary between two states. The runtime drives the future by calling poll, and each call does one of two things:
- It returns
Ready(value)because the future finished. - It returns
Pendingbecause some inner future could not make progress yet.
Between those two outcomes, the future runs ordinary synchronous Rust. Nothing can interrupt it. The executor has no way to pause a function halfway through a line. It only regains control when poll returns.
Cancellation in async Rust means dropping the future. Whoever owns the future, such as timeout, select!, or the runtime holding a spawned task, can only drop it while it is not being polled. So a future can only be cancelled at a point where it just returned Pending.
Code between awaits is never cut short
Here is a job with one await point. The code before the await runs. The code after it does not, because the timeout drops the future while it is suspended.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn job() {
println!("step 1: before the await");
sleep(Duration::from_secs(10)).await;
println!("step 2: never reached");
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(50), job()).await;
println!("timed out: {}", result.is_err());
}The output is step 1: before the await followed by timed out: true. The println! before the await always finishes once the future has been polled. Cancellation can never leave a statement half executed. It can only skip the statements that come after the await it stopped at.
This gives you a practical rule for reading async code. Treat each stretch of code between two .awaits as one indivisible unit with respect to cancellation. Then ask what state the program is in at each .await, because that is where a drop can land.
Locals live in the future
Variables that are alive across an .await are stored inside the future's state machine. When the future is dropped at that await, those variables are dropped too. Their Drop implementations run immediately and synchronously, in the thread that dropped the future. The next chapters cover what to do with this. For now, note that dropping a future is also how its resources are released.
An await that does not suspend is not a cancellation point
.await does not guarantee a pause. If the inner future is already Ready, the .await continues straight through without returning Pending. No pause means no chance to cancel.
async fn add(a: u32, b: u32) -> u32 {
a + b
}An add(1, 2).await completes inside the current poll. The same holds for receiving from a channel that already has a message waiting, or locking a tokio::sync::Mutex that is free. Each of these is a potential suspension point, but on any given call it may not suspend.
A loop made only of awaits that happen to be ready can therefore run for a long time without ever giving the executor a chance to drop it.
Making a CPU-heavy loop cancellable
Pure computation contains no await points, so it cannot be cancelled. If you must do a long computation inside an async function, insert explicit yield points with tokio::task::yield_now. It returns Pending once and wakes the task immediately, so the task goes to the back of the queue and the owner of the future gets a chance to drop it.
use std::time::Duration;
use tokio::task::yield_now;
use tokio::time::timeout;
async fn crunch() {
let mut i: u64 = 0;
loop {
i = i.wrapping_add(1);
if i % 1_000_000 == 0 {
yield_now().await;
}
}
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(50), crunch()).await;
println!("cancelled at a yield point: {}", result.is_err());
}This program prints cancelled at a yield point: true. If you delete the yield_now().await line, crunch never returns from its first poll. The timeout is never given a chance to run, and the program hangs forever. The deadline does not matter, because nothing can act on it.
For work that is heavy and cannot be sliced, such as hashing a large file or calling a blocking library, moving it off the async threads is the right answer. Blocking code and timeouts get their own chapter later in this tutorial.
Multi-step updates across awaits are not atomic
The same rule has a consequence for correctness. If a function changes state, awaits, and then changes more state, cancellation can land between the two changes.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Accounts {
a: i64,
b: i64,
}
async fn transfer(accounts: Arc<Mutex<Accounts>>, amount: i64) {
accounts.lock().unwrap().a -= amount;
sleep(Duration::from_millis(200)).await; // stands in for a remote call
accounts.lock().unwrap().b += amount;
}
#[tokio::main]
async fn main() {
let accounts = Arc::new(Mutex::new(Accounts { a: 100, b: 0 }));
let _ = timeout(Duration::from_millis(50), transfer(accounts.clone(), 30)).await;
let g = accounts.lock().unwrap();
println!("a = {}, b = {}", g.a, g.b);
}The output is a = 70, b = 0. Thirty units were removed from a and never added to b. The timeout dropped the future at the sleep, so the second update was skipped.
The fix is to do all awaiting first and then make the related changes together, with no .await between them. Replace transfer in the program above with this version:
async fn transfer(accounts: Arc<Mutex<Accounts>>, amount: i64) {
sleep(Duration::from_millis(200)).await; // stands in for a remote call
let mut g = accounts.lock().unwrap();
g.a -= amount;
g.b += amount;
}Now a cancelled transfer changes nothing. Either it reaches the lock and finishes both updates in one poll, or it was dropped earlier and touched nothing. Notice that the guard g is a std::sync::MutexGuard that is never held across an .await. Holding it across an await would be a different bug, since that guard is not Send and the compiler will reject it inside a spawned task.
A late deadline is still a deadline
Awaits are the only moments the executor regains control, so a timeout can fire only when the future yields. If a future blocks a thread without awaiting, the deadline passes unnoticed until the next await.
use std::time::{Duration, Instant};
use tokio::time::{sleep, timeout};
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
let slow = async {
std::thread::sleep(Duration::from_millis(200)); // blocks the thread, no await
sleep(Duration::from_secs(10)).await;
};
let result = timeout(Duration::from_millis(50), slow).await;
println!("timed out: {}", result.is_err());
println!("took at least 200 ms: {}", start.elapsed() >= Duration::from_millis(200));
}Both lines print true. The timeout was set to 50 ms but could not act until the future reached its first await after 200 ms. A timeout is a limit on how long a future can go between yields, plus the time it takes to notice. It is not a hard real-time guarantee.
Summary of where cancellation can happen
| Situation | Can the future be dropped here? |
|---|---|
| Between two statements with no `.await` | No. The poll is still running. |
| At an `.await` whose inner future is ready | No. The poll continues. |
| At an `.await` that returns `Pending` | Yes. This is the only place. |
| During a long loop with no awaits | No. The thread is held until the loop ends. |
| At `yield_now().await` | Yes. It always returns `Pending` once. |
| Before the first poll | Yes. The future never ran at all. |
Exercise
A function awaits rx.recv() in a loop and writes each message to a file with synchronous std::fs::write. It is wrapped in timeout(Duration::from_secs(1), ...). A message arrives at 0.9 s and the file write takes 0.5 s. When does the timeout fire, and is the write completed or abandoned?
Show answer
The write is completed. It has no await point, so the poll cannot be interrupted while it runs. The timeout can only fire after the write ends and the loop returns Pending at the next rx.recv(), so it fires at about 1.4 s, later than requested.
Exercise
In the second transfer example, what outcomes are possible if a timeout drops the future, and why can the balances never end up inconsistent?
Show answer
Either the future is dropped during the sleep, which leaves both balances unchanged, or it passes the sleep and runs both updates in one poll with no await between them. A drop cannot happen between the two updates because there is no Pending point there.
Exercise
You add yield_now().await after every iteration of a loop that sums a large vector, hoping to make it cancellable. What is the cost, and what is a better compromise?
Show answer
Each yield costs a trip through the scheduler, which slows the loop when iterations are tiny. Yield only every N iterations, for example when i % 10_000 == 0, so the work between yields stays small enough to cancel promptly but large enough to keep the overhead low.