Sub topic 1
Why async: cooperative concurrency compared with threads
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing, and lifetimes in Rust.
- Traits, generics, and trait objects.
- Enums and pattern matching.
- Basic use of
std::threadandArc. - How to write a simple
async fnand call.awaiton it.
You do not need to know how futures work internally. The rest of the tutorial covers that. This chapter explains why Rust has an async model at all and what trade-offs it makes.
The problem: waiting is the common case
Many programs spend most of their time waiting. A web server waits for bytes from a socket. A client waits for a database reply. A job runner waits for a timer. During these waits the CPU has nothing to do for that particular piece of work.
You want one program to make progress on thousands of such pieces of work at once. This is concurrency: several tasks are in flight, and they take turns using the CPU. It is different from parallelism, where several tasks run at the same instant on different cores. Async Rust mainly targets concurrency for I/O-bound work, though it can also use several cores, as later chapters show.
Concurrency with threads
The standard approach is one operating system (OS) thread per unit of work.
use std::thread;
use std::time::Duration;
fn main() {
let handles: Vec<_> = (0..4)
.map(|i| {
thread::spawn(move || {
// Stand-in for waiting on a network reply.
thread::sleep(Duration::from_millis(100));
i * 2
})
})
.collect();
for handle in handles {
println!("{}", handle.join().unwrap());
}
}The four sleeps overlap, so the program takes about 100 ms, not 400 ms. The OS scheduler does the work. It is preemptive: it can pause any thread at any instruction, save its registers, and run another thread. Your code never has to say "this is a good place to switch."
This is simple and works well for a modest number of threads. The costs show up at scale:
- Memory. Each thread gets its own stack. The default for threads spawned by
std::threadis 2 MiB of reserved address space. The OS commits pages lazily, but thousands of threads still add up in page tables, kernel structures, and guard pages. - Context switches. Switching threads goes through the kernel. It saves and restores CPU state and often disturbs CPU caches. A switch costs on the order of microseconds. That is cheap for a few threads and significant for tens of thousands.
- Limits. The OS caps the number of threads per process and per user. Spawning a thread can fail.
A thread that is blocked in sleep or in a socket read still occupies all of this. It does nothing useful but cannot be reused for other work.
Concurrency with cooperative tasks
Async Rust uses a different model. A task is a unit of work that runs on a thread but is not tied to one thread. Many tasks share a small number of threads. Tasks switch only when they choose to, at an .await point where they cannot make progress. This is cooperative scheduling.
The key mechanism: when a task awaits something that is not ready, it returns control to a component called an executor. The executor then runs another task on the same thread. When the awaited thing becomes ready, the task is scheduled to run again.
async fn greet() -> &'static str {
println!("running");
"hi"
}
fn main() {
let _fut = greet();
println!("created");
}This program prints only created. Calling an async fn runs none of its body. It returns a value, called a future, that describes the work. Something must drive that value for the body to run. That something is the executor, and the next chapters build one.
Because a future is an ordinary value, a task costs roughly the size of that value. The compiler turns an async fn into a state machine that stores only the variables that live across .await points. A task is often hundreds of bytes, not megabytes. Switching between tasks is a normal function return and a normal function call. There is no kernel involvement.
Comparing the two models
| Aspect | OS threads | Async tasks |
|---|---|---|
| Scheduling | Preemptive, by the OS | Cooperative, at `.await` points |
| Cost per unit | Stack (reserved MiB) plus kernel state | Size of the future's state machine |
| Switch cost | Kernel context switch | Function return and call |
| Practical count | Thousands | Hundreds of thousands or more |
| Blocking calls | Fine, they block one thread | Harmful, they block every task on that thread |
| Code shape | Ordinary functions | `async fn`, `.await`, executor required |
| CPU-heavy work | Spreads across cores naturally | Starves other tasks unless moved elsewhere |
Neither model is better in general. Threads are the right default for a small amount of concurrency, for CPU-bound work, and for code that calls blocking libraries. Async fits programs with many concurrent connections or timers that are mostly idle.
Failure modes of cooperative scheduling
Cooperation means the scheduler can only act when a task lets it. This creates problems that threads do not have in the same form.
A task that never yields
Suppose a task runs a long computation with no .await inside it. The executor cannot interrupt it. Every other task on that thread waits until it finishes. The same happens if a task calls a blocking function such as std::thread::sleep or a synchronous file read. The thread is held, and the executor cannot run anything else on it. A later chapter covers runtimes and how to move blocking work to a separate thread pool.
Awaiting is the only switch point
A task can only be paused at .await. This has a useful consequence: between two .await points, the code runs without interruption from other tasks on the same thread. It also means that a loop that awaits something that is always immediately ready may never give other tasks a turn.
Dropping a future cancels it
Since a future is just a value, dropping it before it completes stops the work at its last .await. Threads have no equivalent. You cannot safely kill a thread from outside. Cancellation is powerful, but code that must not stop halfway has to be written with it in mind. A later chapter covers this.
Two kinds of "function"
An async fn can only be awaited from another async context. Synchronous code cannot simply call it and use the result. Libraries often need both blocking and async APIs. This split is a real cost of the model.
What Rust adds
Other languages with async, such as JavaScript or Go, ship a built-in scheduler. Rust does not. The standard library defines the Future trait and the async/await syntax, but no executor. You choose a runtime crate, or write your own. This keeps Rust async usable in embedded devices and operating system kernels, and it avoids a hidden runtime cost for programs that do not use async. The cost is that you need to understand more of the machinery. That machinery is the subject of the remaining chapters: the Future trait, polling, wakers, and Pin.
Exercise
A server handles 50,000 idle connections, each waiting for the client to send data. Why is async tasking a better fit than one thread per connection? Name two concrete costs of the thread approach.
Show answer
Each connection is idle almost all the time, so tasks only need the small state-machine memory for their futures, and a few executor threads can serve all of them. With one thread per connection, each thread reserves a stack (about 2 MiB of address space by default) plus kernel bookkeeping, and the OS scheduler must manage 50,000 threads, with kernel context switches and possible thread-count limits.
Exercise
An async task calls std::thread::sleep(Duration::from_secs(5)) on an executor that has a single thread. What happens to the other tasks during those 5 seconds, and why?
Show answer
They make no progress. Scheduling is cooperative, so the executor can only run another task when the current one returns control at an .await. std::thread::sleep blocks the whole thread without yielding, so the executor has no chance to run anything else until it returns.
Exercise
What does the program async fn f() { println!("hi"); } fn main() { let _x = f(); } print, and why?
Show answer
It prints nothing. Calling an async fn only creates a future. The body does not run until an executor polls that future, and here nothing does.