Sub topic 1
Why Async: Cooperative Concurrency Compared with Threads
Prerequisites
This chapter assumes ownership, borrowing, lifetimes, traits, enums, basic threads, and simple async fn code. You should know that .await can only appear in an asynchronous context.
Cooperative concurrency
A thread is an operating-system execution path. The operating system can interrupt it and switch to another thread. Each thread usually needs its own stack, so many threads can consume substantial memory.
Async tasks are lighter. An async task is a value that makes progress when an executor polls it. Tasks cooperate by returning control when they cannot continue, often while waiting for I/O. One thread can therefore run many tasks.
The `Future` trait
A future is a value representing an operation that may finish later. Rust models it with the Future trait:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
trait MyFuture: Future<Output = u32> {
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Self::Output>;
}The actual standard trait has this same basic shape. The executor calls poll to ask whether the operation has completed.
Polling and readiness
Poll is an enum with two important states:
Poll::Ready(value)means the operation finished.Poll::Pendingmeans it cannot finish yet.
A future must not return Pending and then silently forget to notify the executor. Its Context contains a Waker, which lets the future request another poll when progress becomes possible.
What `async fn` and `.await` produce
Calling an async fn does not immediately run its body. It returns an unnamed type that implements Future. The body starts when that future is polled.
async fn add(a: u32, b: u32) -> u32 {
a + b
}
async fn run() -> u32 {
let x = add(1, 2).await;
x * 2
}.await asks the executor to poll the awaited future. If it is pending, the surrounding future also pauses.
Async code as a state machine
The compiler transforms an async body into a state machine. Each .await creates a possible suspension point. The state machine stores local variables that must survive that suspension and resumes from the correct state later. This transformation explains why async functions return futures and why their types are usually hidden.
Exercise
What should an executor do after a future returns Poll::Pending?
Show answer
Wait until the future's waker signals progress, then poll it again.