Sub topic 1
Why async? Waiting without blocking a thread
Prerequisites
This chapter assumes you are comfortable with the following:
- Rust ownership, borrowing, and closures with
move. - Spawning a thread with
std::thread::spawnand joining it. - Adding a dependency with feature flags in
Cargo.toml. Resultand the?operator.
You do not need to know anything about Future, async, or .await yet. The later chapters cover them. Here you will see the problem async solves and the cost model behind it.
The problem: programs spend most of their time waiting
Many programs do little computation. A web server reads a request from a socket, queries a database, calls another service, and writes a response. Almost all of the elapsed time goes to waiting for the network or the disk, not to running CPU instructions.
This kind of work is called I/O-bound. The opposite is CPU-bound work, such as hashing, compressing, or parsing a large file, where the processor is busy the whole time.
The question is what your program does while it waits.
The thread-per-task model
The simplest answer is to give each unit of work its own operating system thread and let the thread block. A blocked thread is parked by the OS scheduler and uses no CPU until the data arrives.
use std::thread;
use std::time::{Duration, Instant};
fn main() {
let start = Instant::now();
let mut handles = Vec::new();
for id in 0..3u32 {
handles.push(thread::spawn(move || {
thread::sleep(Duration::from_millis(200));
id
}));
}
for h in handles {
println!("finished {}", h.join().unwrap());
}
println!("elapsed: {:?}", start.elapsed());
}All three waits overlap, so the total is about 200 ms rather than 600 ms. This model is simple and works well for tens or hundreds of tasks. Ordinary blocking code, ?, and the borrow checker all behave as you expect.
The cost shows up when the task count grows:
- Memory. Each thread has its own stack. Rust's standard library reserves 2 MiB of address space per spawned thread by default. The OS commits pages lazily, but the bookkeeping per thread is still real, and 10,000 threads is a heavy load.
- Scheduling. The kernel switches between threads. Each switch saves and restores registers and can evict useful data from CPU caches.
- Limits. Operating systems cap the number of threads per process or per user. Hitting that cap is a common failure in servers that hold many idle connections.
Most of those threads would do nothing but wait. You pay for a full stack and a kernel scheduling entry to represent "I am waiting for bytes on a socket".
The async model
Async programming separates the idea of a task from the idea of a thread. A small number of threads, often one per CPU core, run many tasks. When a task reaches a point where it must wait, it does not block its thread. It tells the runtime "I can't continue yet" and gives the thread back. The runtime then runs another task on that thread. When the awaited event happens, the runtime resumes the waiting task.
A task that waits like this is called suspended. A suspended task is not a stack plus a kernel thread. It is an ordinary Rust value in memory that stores only the data it needs to continue. You will see in a later chapter that the compiler builds this value as a state machine, and that its size is often a few hundred bytes.
Here is the same idea at a larger scale, using Tokio. Add it to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }Then run 10,000 tasks that each wait one second:
use std::time::{Duration, Instant};
#[tokio::main]
async fn main() {
let start = Instant::now();
let mut handles = Vec::new();
for i in 0..10_000u32 {
handles.push(tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(1)).await;
i
}));
}
let mut total = 0u64;
for h in handles {
total += u64::from(h.await.unwrap());
}
println!("sum {total} in {:?}", start.elapsed());
}The sum is 49995000, and the elapsed time is a little over one second. The program did not create 10,000 threads. It created 10,000 small task values and ran them on the runtime's worker threads. Do not worry about tokio::spawn, async move, or .await yet. Later chapters explain each one.
What you pay for async
Async is not free, and it is not faster at everything.
| Concern | Threads | Async tasks |
|---|---|---|
| Cost per waiting unit | A stack and a kernel entry | A small heap value |
| Practical count | Hundreds to low thousands | Hundreds of thousands |
| Code style | Plain blocking calls | `async fn` and `.await` |
| Blocking call in the code | Harmless to other threads | Stalls every task on that worker thread |
| Needs a runtime | No | Yes (the standard library does not include one) |
| Best for | CPU-bound work, simple programs | Many concurrent I/O waits |
Three points deserve attention.
- Async adds a runtime and new rules. Rust's standard library defines
async,.await, and theFuturetrait, but it does not ship an executor. You choose a runtime crate such as Tokio. - Async does not speed up computation. A task that crunches numbers occupies its worker thread until it finishes. Async helps only when tasks spend time waiting.
- Blocking inside async is the typical mistake. Calling
std::thread::sleepor a blocking file read inside a task blocks the whole worker thread, so every other task on it stops making progress.
The code below shows the mistake. Do not copy it into real programs:
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let slow = tokio::spawn(async {
// Blocks the only worker thread for two seconds.
std::thread::sleep(Duration::from_secs(2));
println!("slow done");
});
let quick = tokio::spawn(async {
println!("quick done");
});
slow.await.unwrap();
quick.await.unwrap();
}With a single worker thread, quick cannot print until slow returns, even though quick has nothing to wait for. A later chapter shows the correct tools, including spawn_blocking.
Choosing between threads and async
Use threads when the work is CPU-bound, when you have a modest number of concurrent operations, or when a blocking library is the only option. Use async when you must hold many connections or timers open at once, as in network servers, proxies, and clients that fan out many requests. Programs often use both: an async runtime for I/O, with a thread pool for heavy computation.
What comes next
The following chapters explain how Rust makes this work. A Future is a value that reports whether it is ready. async fn creates futures for you. .await waits for one without blocking the thread. A runtime polls futures and resumes them when the data arrives.
Exercise
A service must keep 50,000 idle client connections open, and each connection spends nearly all its time waiting for the client to send data. Give two reasons a thread-per-connection design is a poor fit, and say why async tasks fit better.
Show answer
First, 50,000 threads each need their own stack, so memory and kernel bookkeeping are large, and the OS may refuse to create that many threads. Second, the kernel must schedule and context-switch among them, which wastes CPU for threads that do nothing but wait. Async tasks fit better because a waiting task is a small value rather than a stack and a kernel thread, and a few worker threads can run whichever tasks have data ready.
Exercise
In the single-threaded Tokio program above that calls std::thread::sleep, why does quick not print until two seconds have passed?
Show answer
The runtime has one worker thread, and std::thread::sleep blocks that thread without yielding to the runtime. The runtime cannot run quick until the slow task returns control, which happens only after the sleep ends.