Sub topic 12
Executors and tasks: building a minimal block_on
This chapter assumes you know what Future, Poll, Context, and Waker are, and that you can pin a value with pin!. A future does nothing until something polls it. That something is an executor. Here you will build the smallest useful one.
What an executor does
An executor owns futures and calls poll on them. When poll returns Poll::Pending, the executor stops polling that future until its waker is called. When it returns Poll::Ready, the executor takes the output and is done with it.
block_on is the simplest executor. It runs one future on the current thread and returns its output.
The waker
A Waker needs to know how to wake your executor. The Wake trait lets you build one from an Arc. Our waker holds a handle to the thread that called block_on and unparks it.
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(),
}
}
}Three details matter here:
pin!(fut)pins the future on the stack. The future cannot move again, so it is safe to poll even if it is self-referential.fut.as_mut()gives a freshPin<&mut F>on each iteration.polltakesself: Pin<&mut Self>by value, so withoutas_mutthe pin would be consumed on the first call.thread::park()blocks until another thread callsunpark. Ifunparkwas already called,parkreturns immediately. This means a wake that arrives betweenpollandparkis not lost.
Running it
Put these in the same file as block_on, along with the CountDown future from the previous chapter, or any future you like:
async fn add(a: u32, b: u32) -> u32 {
a + b
}
async fn run() -> u32 {
let x = add(1, 2).await;
x * 2
}
fn main() {
println!("{}", block_on(run()));
}This prints 6. Nothing in run is actually pending, so block_on polls once and returns. With CountDown(3), the executor polls four times. Each Pending result comes with a wake_by_ref call, so park returns right away.
From block_on to tasks
A task is a top-level future that an executor owns and polls independently. A real runtime keeps a queue of tasks. Each task's waker pushes that task back onto the queue, and worker threads pop tasks and poll them. Your block_on has exactly one task and uses the thread itself as the queue.
Exercise
Why does blockon call fut.asmut().poll(&mut cx) instead of fut.poll(&mut cx) inside the loop?
Show answer
poll takes self: Pin<&mut Self> by value. Calling it on fut directly would move the Pin into the call, so it could not be used on the next iteration. as_mut reborrows the pin, leaving fut available for the next loop pass.
Exercise
What would go wrong if block_on called thread::sleep in the Pending branch instead of thread::park?
Show answer
The executor would wait a fixed time whether or not the future was woken. It would add latency when a wake arrives early and waste polls when it arrives late. Parking ties the wait to the waker.