Sub topic 1
Futures Do Nothing Until Polled
Prerequisites
Assume you know Rust ownership, borrowing, Drop, and basic async/await syntax. You should also know how #[tokio::main] starts a Tokio runtime.
An async function does not run when it is called. It creates a future, which is a value describing work that can run later. The runtime runs that work by repeatedly polling the future.
use std::time::Duration;
use tokio::time::sleep;
async fn work() {
println!("started");
sleep(Duration::from_millis(10)).await;
println!("finished");
}
#[tokio::main]
async fn main() {
let future = work();
println!("future created");
future.await;
}The output starts with future created. Calling work() alone would print nothing because the returned future was never polled.
Await Points Are Where a Task Can Stop
An .await checks whether an inner future is ready. If it is not ready, the outer task returns Poll::Pending to the runtime. The runtime can then run another task and poll this task again later.
The task can make progress between await points. It cannot be interrupted at an arbitrary Rust statement. This matters when reasoning about shared state and cleanup: cancellation takes effect when the future is dropped, and a task normally reaches that state at an await boundary.
flowchart TD
A[Runtime polls future] --> B{Ready?}
B -- No --> C[Future returns Pending]
C --> D[Runtime polls another task]
D --> A
B -- Yes --> E[Future returns a value]Cancellation Means Dropping the Future
Rust has no automatic cancellation instruction for every async operation. The basic mechanism is drop. When a future is dropped, its local values are dropped too, and its remaining code does not run.
A timeout or select! can therefore stop an operation by dropping the losing future. Resources held by that future should use normal ownership and Drop cleanup.
Bounding Work with `timeout`
tokio::time::timeout races an operation against a deadline. It returns Ok(value) if the operation finishes first, or Err(Elapsed) if the deadline wins. The inner future is then dropped.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(100), sleep(Duration::from_secs(5))).await {
Ok(()) => println!("finished"),
Err(_) => println!("timed out"),
}
}A timeout does not interrupt blocking synchronous code. The operation must yield to the runtime for Tokio to observe the deadline.
Exercise
What happens to the future passed to timeout when the deadline finishes first?
Show answer
Tokio returns Err(Elapsed) and drops the inner future, so its remaining async work does not run.