Sub topic 1
Why async? Waiting without blocking a thread
Prerequisites
This chapter assumes you know Rust ownership and borrowing, traits and generics, and the Result type with the ? operator. You should also know what a thread is and why programs use several of them. The examples later in the tutorial use Cargo dependencies with feature flags, but this chapter needs no setup.
Why async? Waiting without blocking a thread
Many programs spend most of their time waiting. A web server waits for packets, a database client waits for a reply, and a timer waits for a deadline. This is I/O-bound work: the CPU is idle while something outside the program makes progress.
The simplest way to handle many waits is one operating system thread per task. A blocking call parks that thread until the data arrives. This works, but each thread costs memory for its stack, and the operating system pays to switch between them. With tens of thousands of connections, the cost becomes a problem.
Async code takes a different approach. A task that must wait gives up the thread, so the thread can run other work. When the awaited event happens, the task resumes. A small number of threads can then serve a large number of waiting tasks.
| Approach | Cost per waiting task | Best for |
|---|---|---|
| Thread per task | An OS thread and its stack | Few tasks, CPU-heavy work |
| Async task | A small state object | Many tasks that mostly wait |
Async does not make a single operation faster. It lets one thread overlap many waits.
The Future trait and Poll
In Rust, a value that represents work that may not be finished yet is a future. It is any type that implements the Future trait from the standard library. The trait has one required method, poll.
use std::pin::Pin;
use std::task::{Context, Poll};
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}Calling poll asks the future to make progress. It returns a Poll, which has two variants:
Poll::Ready(value)means the work is done andvalueis the output.Poll::Pendingmeans the work is not done. The future has arranged to be woken when it can continue.
A component called an executor calls poll. If the result is Pending, the executor runs other futures and does not poll this one again until it is woken. The Context argument carries the waker that does the waking. Later chapters cover wakers and Pin. For now, treat them as plumbing.
Here is a hand-written future that is pending once, then ready.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct YieldOnce {
yielded: bool,
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}The first poll sets the flag, asks to be woken, and returns Pending. The second poll returns Ready. Calling wake_by_ref before returning Pending matters. If a future returns Pending without arranging a wake-up, the executor never polls it again and the task hangs.
Exercise
What are the two variants of Poll, and what must a future do before it returns the one that means "not finished"?
Show answer
The variants are Poll::Ready(value) and Poll::Pending. Before returning Pending, the future must arrange for its waker to be called when it can make progress, for example by calling cx.waker().wake_by_ref() or storing the waker for an event source to call.
Exercise
Why can one async thread serve more waiting connections than a thread-per-connection design?
Show answer
A waiting async task returns Pending and releases the thread, so the thread can poll other tasks. Each waiting task costs only a small state object, not a whole OS thread and stack.