Sub topic 3
What a runtime adds: executor and reactor
This chapter assumes you know what async fn and .await do, and that a future is a value with a poll method returning Poll::Ready or Poll::Pending. You should also be comfortable with Arc, traits and closures. Here we look at what has to exist around a future before it makes progress, and what Tokio supplies.
Futures do nothing on their own
The standard library gives you the Future trait and the async syntax. It does not give you anything that calls poll. A future that nobody polls never runs, not even its first line.
async fn greet() {
println!("hello from the future");
}
#[tokio::main]
async fn main() {
let fut = greet();
println!("future created");
fut.await;
}The output is future created, then hello from the future. Calling greet() only builds a state machine. The body runs when something polls it, which here happens at fut.await.
Something must therefore sit outside your code and do three jobs:
- Call
pollon futures. - Notice when the outside world is ready, for example a socket has data or a timer has expired.
- Poll the right future again when that happens, and only then.
Tokio splits these jobs between an executor, a reactor and a timer driver.
The executor
The executor owns the tasks and decides which one to poll next. A task is a top-level future that has been handed to the runtime, for example with tokio::spawn or block_on. Futures you .await inside a task are part of that task's state machine. They are not separate tasks.
An executor has three parts:
- A run queue of tasks that are ready to be polled.
- One or more worker threads that take tasks from the queue and call
poll. - A
Wakerfor each task. Callingwake()puts the task back on the run queue.
A worker polls a task until it returns Pending or Ready. If Pending, the worker drops the task from its hands and moves to the next one. The task is not queued again until someone calls its waker. This is why an async runtime can run thousands of tasks on a few threads. A waiting task costs memory but no thread time.
The following executor is deliberately tiny. It runs one future on the current thread and parks the thread whenever the future is pending.
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(),
}
}
}
fn main() {
let value = block_on(async { 1 + 2 });
println!("{value}");
}The waker here unparks the thread. Tokio's wakers do something similar but push a task onto a queue. This executor works for futures that finish without outside events. It cannot run tokio::time::sleep or a TcpStream. Those futures need the other half of the runtime.
The reactor
The reactor watches things that become ready outside your program. In Tokio, the I/O driver is built on mio, which wraps the operating system's readiness API (epoll on Linux, kqueue on macOS and BSD, IOCP on Windows). The flow for a socket read is:
- A task calls
socket.read(&mut buf).await. - The read future tries the read. The OS says "would block", so the future registers interest in this socket with the reactor. It stores the task's waker (taken from the
Context) and returnsPending. - When no task is runnable, a worker blocks inside the driver, waiting for OS events.
- The OS reports that the socket is readable. The reactor finds the stored waker and calls
wake(). - The task goes back on the run queue. A worker polls it again, the read succeeds, and the future returns
Ready.
Timers follow the same pattern with a different driver. sleep registers a deadline in Tokio's timer wheel. The runtime computes how long it may block in the I/O driver, so it wakes up at the next deadline, fires the expired timers and calls their wakers.
Because the fence must follow the chapter's required format, here is the diagram in full:
Where the pieces live in Tokio
Tokio bundles the executor, the I/O driver and the timer driver into one Runtime. Each driver is a feature you can turn on or off. #[tokio::main] is shorthand for building a runtime and running your main body on it. You can do that by hand:
use std::time::Duration;
use tokio::runtime::Builder;
use tokio::time::sleep;
fn main() {
let rt = Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let out = rt.block_on(async {
sleep(Duration::from_millis(50)).await;
"done"
});
println!("{out}");
}enable_all() turns on both the I/O and time drivers. If you build a runtime without them, sleep and network types fail at run time instead of compiling away. block_on runs a future on the calling thread and returns its output. Spawned tasks run on the worker threads.
Common errors
Most runtime mistakes come from forgetting that the executor and drivers are separate from your futures.
| Symptom | Cause | Fix |
|---|---|---|
| Panic: "there is no reactor running, must be called from the context of a Tokio runtime" | You created a Tokio I/O or timer type (or called `tokio::spawn`) on a thread with no runtime context | Run the code inside `block_on`, a spawned task, or after `rt.enter()` |
| Timers never fire, or panic about the time driver | The runtime was built without `enable_time()` | Use `enable_all()` or `enable_time()` |
| Nothing prints and the program exits | You built a future and never awaited or spawned it | `.await` it or pass it to `tokio::spawn` |
| Panic: "Cannot start a runtime from within a runtime" | You called `block_on` inside async code | Use `.await`, or `spawn_blocking` for blocking work |
| One slow task freezes others | The task never returns `Pending`, so the worker cannot poll anything else | Add `.await` points or move the work to `spawn_blocking` |
| Futures hang when using a different runtime's types | Wakers were registered with a reactor that is not running, for example async-std types on Tokio | Use one runtime's I/O and timer types per program |
What the runtime does not do
The runtime does not make blocking calls asynchronous. std::thread::sleep, std::fs::read and a long CPU loop block a worker thread directly, and the reactor cannot help. It also does not run .awaited futures in parallel. Awaiting two futures in sequence inside one task runs them one after the other. Concurrency comes from having more than one task, or from combinators such as join!, which later chapters cover.
Exercise
A task awaits TcpStream::read, and no data has arrived yet. Which component stores the task's waker, which component calls it, and what happens to the worker thread in the meantime?
Show answer
The read future stores the waker (copied from the Context passed to poll) in the reactor's registration for that socket, then returns Pending. When the OS reports the socket readable, the reactor (I/O driver) calls wake(), which puts the task back on the executor's run queue. Meanwhile the worker thread is not tied to the task. It polls other ready tasks, or blocks in the driver if none are ready.
Exercise
You run block_on(async { tokio::time::sleep(Duration::from_millis(10)).await }) using the hand-written block_on from this chapter. It panics. Why, and what is the smallest change that makes it work?
Show answer
sleep needs a Tokio runtime context with the time driver enabled. The hand-written executor has no timer driver, so the panic happens when the sleep is created or polled. The smallest fix is to run the future with a Tokio runtime, for example Builder::new_current_thread().enable_time().build().unwrap().block_on(...).