Sub topic 2
How futures are polled: Poll and Waker
This chapter assumes you know Rust ownership, traits, and closures, and that you have seen async fn and .await. It also assumes you can run a Cargo project. You don't need Tokio here. The examples use only the standard library, so you can see what any runtime must do for you.
The Future trait
A future is a value that describes work that may not be finished yet. The standard library defines it with one required method:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}Creating a future does nothing by itself. Work happens only when someone calls poll. That caller is an executor, which is the part of a runtime that runs futures. The next chapter covers it.
Pin<&mut Self> guarantees the future will not move in memory while it is being polled. This matters because an async block can hold references into its own fields across an .await. This chapter uses types that are safe to move, so pinning stays in the background.
Poll: ready or not yet
poll returns a Poll value:
pub enum Poll<T> {
Ready(T),
Pending,
}Poll::Ready(value)means the future has finished and producedvalue.Poll::Pendingmeans it cannot finish yet, andpollreturned without blocking the thread.
Returning quickly is the central rule. A poll call should do whatever work it can, then return. If it blocks, every other future on that thread stalls.
Waker: how a future asks to be polled again
If poll returns Pending, the executor needs to know when to try again. Polling in a tight loop would waste CPU. Instead, the future receives a Waker through the Context argument and makes this promise:
> When I can make progress, I will call wake on the waker you gave me.
This is the whole contract. The executor polls a future, sees Pending, and sets it aside. Later, something calls wake, and the executor puts the future back in its queue and polls it again.
That fence was written incorrectly above, so here is the diagram in the required format.
A minimal executor
The program below implements block_on, the smallest possible executor. It polls one future on the current thread. When the future returns Pending, the thread parks (sleeps). The waker unparks it. The Countdown future returns Pending a few times and wakes itself each time.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = std::pin::pin!(fut);
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
struct Countdown {
remaining: u32,
}
impl Future for Countdown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.remaining == 0 {
Poll::Ready("liftoff")
} else {
println!("poll: {} left", self.remaining);
self.remaining -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
fn main() {
let result = block_on(Countdown { remaining: 3 });
println!("{result}");
}The program prints poll: 3 left, poll: 2 left, poll: 1 left, then liftoff.
wake_by_ref runs before Pending is returned, so the unpark happens before the thread parks. This is safe. unpark leaves a token behind, and the next park returns immediately. Real executors rely on the same property: a wake that arrives early is not lost.
A future that waits for something external
Countdown wakes itself, which is just a busy loop with extra steps. A useful future waits for an event outside the poll loop. It stores the waker where the event source can reach it.
The Delay future below does this. A helper thread sleeps, marks the shared state as done, and calls the stored waker. Add this code to the same file, add use std::sync::Mutex; and use std::time::Duration; to the imports, and replace main.
struct Shared {
done: bool,
waker: Option<Waker>,
}
struct Delay {
shared: Arc<Mutex<Shared>>,
}
impl Delay {
fn new(dur: Duration) -> Self {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let thread_shared = Arc::clone(&shared);
thread::spawn(move || {
thread::sleep(dur);
let mut s = thread_shared.lock().unwrap();
s.done = true;
if let Some(w) = s.waker.take() {
w.wake();
}
});
Delay { shared }
}
}
impl Future for Delay {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.shared.lock().unwrap();
if s.done {
Poll::Ready(())
} else {
s.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
fn main() {
block_on(async {
println!("waiting");
Delay::new(Duration::from_millis(200)).await;
println!("done");
});
}Two details matter here.
- The waker is saved on every
Pending. The executor may pass a different waker on each poll, for example after the task moves to another thread. Always store the most recent one, replacing the old one. - The mutex covers both the flag and the waker. If the timer thread set
donebetween the check and the store, the wake would be lost and the future would hang forever. Holding the lock across both steps closes that gap.
How `.await` uses all of this
The compiler turns each async block or async fn into a state machine that implements Future. Each .await becomes a point where the machine calls poll on the inner future, passing along the same Context.
- If the inner future returns
Ready, the machine continues to the next step. - If it returns
Pending, the machine saves its state and also returnsPending.
So Pending travels up through every layer of .await to the executor, and the waker travels down through the same Context. The innermost future, such as a timer or socket, is the one that stores the waker. Tokio's sleep and TcpStream::read are leaf futures of this kind.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning `Pending` without arranging a wake | Task hangs forever, no error | Store `cx.waker()` somewhere the event source can reach, or call `wake_by_ref` |
| Checking state and storing the waker without a lock or atomic ordering | Rare hangs from a lost wakeup | Make check-and-register one atomic step |
| Blocking inside `poll` (`thread::sleep`, blocking I/O) | Other tasks on the thread stop making progress | Return `Pending` and wake later, or move the work to `spawn_blocking` |
| Polling a future again after it returned `Ready` | May panic, hang, or misbehave | Stop polling once `Ready` is returned |
| Holding an old waker and never refreshing it | Wakes go to the wrong task | Replace the stored waker on every `Pending` |
Where Tokio fits
You rarely implement Future by hand when using Tokio. Its timers, sockets, and channels already contain the poll and waker logic. What you gain from knowing the model is a way to reason about behavior:
- A task makes progress only while it is being polled, so a long stretch of work between two
.awaitpoints holds up everything else on that thread. Pendingis cheap, so thousands of tasks can wait on I/O at once.- Dropping a future simply stops polling it. This is the basis for cancellation, covered in a later chapter.
The next chapter looks at the executor and reactor, the two components that call poll and call wake.
Exercise
In the Delay example, suppose poll returned Pending without storing cx.waker() in the shared state. What would happen when you run block_on on it, and why?
Show answer
The program would hang after printing "waiting". The helper thread would set done to true, but it would find no waker to call, so nothing would unpark the main thread. block_on would stay parked inside thread::park(), and the future would never be polled again to see that done is true.
Exercise
Why does Countdown call cx.waker().wake_by_ref() before returning Poll::Pending, and what would go wrong if it did not call it?
Show answer
block_on parks the thread after every Pending and only resumes when the waker is called. Without the call, nothing would ever unpark the thread, so the program would hang after the first poll. Calling wake_by_ref first is safe because unpark leaves a token, so the following park returns immediately.