Sub topic 1
Why async? Waiting without blocking a thread
Prerequisites
This chapter assumes Rust ownership, borrowing, lifetimes, traits, generics, Result, closures, and basic thread and concurrency concepts. You should also know how to add a dependency to Cargo.toml.
Waiting without blocking
A synchronous function blocks its thread while it waits for a timer, file, or network response. An asynchronous function can pause during that wait. The runtime uses the thread to run other work instead.
Async is useful for I/O-bound work, where a program spends much of its time waiting. It does not automatically make CPU-heavy work faster.
The Future trait and Poll
A Future is a value representing work that may finish later. Its poll method lets an executor ask whether the work is complete.
poll returns:
Poll::Ready(value)when the work has finished.Poll::Pendingwhen it needs to wait. The future arranges for its waker to notify the executor when polling should resume.
This design avoids dedicating one blocked thread to every waiting operation.
Writing async fn and async blocks
An async fn does not return its final value directly. It returns a future that will produce that value. An async block creates a future in the same way.
The await expression asks the runtime to drive a future until it produces a value.
use std::time::Duration;
use tokio::time::sleep;
async fn greet(name: &str) -> String {
sleep(Duration::from_millis(100)).await;
format!("Hello, {name}!")
}
#[tokio::main]
async fn main() {
let message = greet("Ferris").await;
println!("{message}");
let future = async {
println!("running");
2 + 2
};
println!("created");
let answer = future.await;
println!("{answer}");
}Add Tokio with its full feature set in Cargo.toml. The #[tokio::main] macro creates a Tokio runtime and starts it before calling main.
Futures are lazy
Creating a future does not start its work. In the example, created prints before running because the async block begins only when future.await causes it to be polled.
A future can also be polled by combinators such as join!, or by a spawned Tokio task. Without an executor or runtime, it will not make progress.
Exercise
What does Poll::Pending mean, and when does an async block begin running?
Show answer
Poll::Pending means the future is not complete and will be polled again after its waker signals progress. An async block begins when an executor polls it, often because code awaits it.