Sub topic 12
Executors and Tasks: Building a Minimal block_on
This chapter assumes you know what Future, Poll, Context, and Waker are, and how Pin<&mut T> appears in the signature of poll. Here you put those pieces together into an executor. An executor is the code that actually calls poll. Without one, a future does nothing.
What an executor does
A future is inert. Calling an async fn returns a value, and nothing runs until someone calls poll on it. That someone is the executor. It has three jobs:
- Own the future, or a pointer to it, so that it stays pinned in one place.
- Call
pollwith aContextthat holds aWaker. - When
pollreturnsPending, stop polling that future until its waker is called.
The third job is what separates an executor from a busy loop. Polling in a tight loop would work, but it would burn a CPU core while waiting. A real executor sleeps and lets the waker wake it.
The smallest useful executor is block_on. It runs one future to completion on the current thread and returns its output. It is how a synchronous main can call async code. Runtimes such as Tokio build on the same idea, with a task queue and many worker threads.
The pieces of block_on
block_on needs four things.
- Pinning.
polltakesPin<&mut Self>, so the future must be pinned before the first poll. Thestd::pin::pin!macro pins it on the stack, so no heap allocation is needed. - A waker. Implementing the
std::task::Waketrait is the safe way to make one.Waker::from(Arc<W>)turns anyW: Wake + Send + Sync + 'staticinto aWaker. - A context.
Context::from_waker(&waker)wraps the waker. This is thecxthat futures receive inpoll. - A sleep mechanism.
thread::park()blocks the thread.Thread::unpark()wakes it. This pair fits the waker's job exactly.
Here is the executor.
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 = 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(),
}
}
}Several details matter here.
pin!(fut) moves fut into a hidden local variable and gives back a Pin<&mut F>. The original name fut is shadowed, so you cannot move the future again. That is the point of the macro.
fut.as_mut() reborrows the pinned reference as a fresh Pin<&mut F>. poll consumes its Pin<&mut Self> argument. Without as_mut, the first call would move fut, and the loop could not poll again.
ThreadWaker stores a Thread handle captured by thread::current(). Any thread can call wake, and the handle always refers to the thread that is running block_on.
Why park and unpark do not lose wakeups
Suppose a future calls wake_by_ref inside poll, before returning Pending. The waker calls unpark while the thread is still running. Does the later park then sleep forever?
No. Each thread has a one-time token. unpark sets the token if the thread is not parked. The next park finds the token, clears it, and returns at once. A wakeup that arrives early is therefore never lost.
The reverse case is a spurious wakeup, where park returns without anyone calling unpark. The platform is allowed to do this. It is harmless here, because the loop just polls again. A correct future must tolerate extra polls and return Pending again if it is still not ready.
Running it with a hand-written future
This complete program combines block_on with the countdown future from the previous chapter. It also mixes in an async fn, so you can see both kinds of future driven by the same loop.
use std::future::Future;
use std::pin::{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 = 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(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
println!("pending, {} left", self.0);
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
async fn add(a: u32, b: u32) -> u32 {
a + b
}
async fn run() -> u32 {
let msg = CountDown(3).await;
println!("{msg}");
add(1, 2).await * 2
}
fn main() {
println!("result = {}", block_on(run()));
}The program prints this:
pending, 2 left
pending, 1 left
pending, 0 left
done
result = 6block_on polls the outer future four times. The first three polls reach CountDown, which returns Pending and wakes itself. The Pending result passes up through run, because .await returns Pending from the enclosing future. On the fourth poll, CountDown is ready and run continues to the end.
The sequence below shows one Pending round.
From block_on to tasks
block_on runs exactly one future. A general executor runs many. It needs a unit of work that it can schedule, and that unit is the task.
A task is a top-level future that the executor owns, plus the bookkeeping needed to poll it again later. Typically a task holds:
- the future, boxed and pinned, usually as
Pin<Box<dyn Future<Output = ()> + Send>> - a handle that can put the task back on the executor's ready queue
The waker for a task is built from that handle. Calling wake pushes the task onto the queue, and a worker thread later pops it and polls it. This is why Wake takes self: Arc<Self>. The Arc lets the task be shared between the executor and every waker clone that I/O sources are holding.
| Aspect | `block_on` | Task-based executor |
|---|---|---|
| Futures at once | One | Many |
| Where the future lives | Caller's stack, via `pin!` | Heap, via `Box::pin` |
| What `wake` does | Unparks one thread | Re-queues one task |
| Sleep when idle | `thread::park` | Park workers until the queue has work |
| Output type | Any `F::Output` | Usually `()` per task |
Spawning is just creating a task. spawn(fut) boxes the future, pins it, wraps it in a task, and pushes it onto the queue. Unlike block_on, spawn returns right away. Spawned futures typically need to be 'static, because the task may outlive the function that created it. Multi-threaded executors also need them to be Send, which a later chapter covers.
Common errors
- Returning
Pendingwithout arranging a wakeup. The executor parks and nobody wakes it, so the program hangs. EveryPendingmust be backed by a stored waker, or a call towakeas inCountDown. - Calling
block_oninside an async context. It blocks the thread, which stalls any other tasks on that worker. Use it only at the synchronous edge of your program. - Polling after
Ready. TheFuturecontract allows panics or other misbehavior if you poll again after completion. Thereturninblock_onprevents this. - Moving the future after the first poll. Pinning prevents this at the type level, which is why
pin!hides the original binding.
Exercise
In block_on, why is the call written as fut.as_mut().poll(&mut cx) instead of fut.poll(&mut cx), and what would go wrong without as_mut?
Show answer
poll takes self: Pin<&mut Self> by value. Calling fut.poll(...) would move the Pin<&mut F> into the first call, so the second loop iteration could not use fut again and the code would not compile. as_mut() creates a short-lived reborrowed Pin<&mut F> for each call and leaves fut available.
Exercise
A future returns Poll::Pending but never stores or calls the Waker it was given. What happens when it runs under block_on, and why?
Show answer
The program hangs. block_on calls thread::park() after Pending, and only the waker's unpark can end that sleep. With no wake call, nothing sets the token, so the thread sleeps forever, apart from a rare spurious wakeup, which would just trigger one extra poll.