In a Rust async runtime, what is the difference between the executor and the reactor, and which does `futures::executor::block_on` provide?
answer
- who polls vs who waits on the OS
- the Waker connects the two
- park until unparked
- smol splits them into crates
basics
~20 sThe executor polls woken tasks; the reactor waits on the operating system for I/O and timers and calls the stored Waker. futures::executor::block_on is only an executor: it polls, then parks the thread until the waker unparks it.
solid answer
~40 sA Rust runtime has two jobs. The **executor** owns tasks and calls `poll` on each one when it has been woken. The **reactor** registers sockets and timers with the operating system (epoll, kqueue or IOCP), blocks waiting for events, and when one arrives calls the `Waker` that the pending I/O future stored, which puts the task back in the executor's queue. `futures::executor::block_on` is only an executor: it polls the future and, on `Poll::Pending`, parks the thread until the future's waker unparks it. It can finish any future whose wake-up comes from elsewhere, such as a channel fed by another thread or smol's timers, but it cannot drive I/O types that need a particular runtime's reactor running. smol shows the split: `async-executor` provides `Executor`, and `async-io` provides the reactor behind `Async<T>` and `Timer`.
code
rust · 32 linesuse std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
// The waker's whole job: unpark the thread that is waiting in block_on.
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
// An executor with no reactor: poll, and park until something calls wake.
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(v) => return v,
Poll::Pending => thread::park(),
}
}
}
fn main() {
let answer = block_on(async { 6 * 7 });
println!("{answer}");
}go deeper
Recall the two roles: the executor polls tasks, the reactor waits for I/O and timers, and the Waker is how the reactor tells the executor a task can run.
Explain what futures::executor::block_on does on Pending, why it has no reactor, and which smol crates provide the executor and the reactor.
Use the split to debug: a future that hangs under a minimal executor usually has nobody to call its waker because its reactor is not running.
Use the split when setting library policy: code that only combines futures stays executor-agnostic, while code that opens sockets binds callers to one reactor.
## Two jobs inside every runtime Rust's `Future` contract is runtime-agnostic: a future says "not yet" by returning `Poll::Pending`, after arranging for the `Waker` from its `Context` to be called when it can make progress. Two separate pieces of a runtime make that contract useful: - **Executor**: keeps a queue of tasks, calls `poll` on a task when it is ready to run, and leaves it alone otherwise. It knows nothing about sockets. - **Reactor**: knows about sockets, pipes and timers. It registers interest with the operating system, blocks in a single call such as epoll, kqueue or IOCP until something happens, and then calls the `Waker` associated with each event. The `Waker` is the only connection between them. An I/O future asked for a read that would block registers its waker with the reactor and returns `Pending`; the reactor later calls `wake`; the executor sees the task re-queued and polls it again. ## What `futures::executor::block_on` actually is The futures crate's `block_on` is the simplest possible executor for one future. In version 0.3 it pins the future, builds a `Waker` that unparks the current thread, and loops: 1. poll the future; on `Poll::Ready(v)`, return `v`; 2. on `Poll::Pending`, call `std::thread::park` until the waker has been called; 3. go back to step 1. There is **no reactor** in it. That is not a defect; it is what makes it small and portable among std targets. It completes: - futures that are ready straight away or are built from other such futures; - futures woken by another thread, for example the receiving half of a channel whose sender lives on a `std::thread`; - futures whose reactor runs somewhere else. smol's `async-io` crate starts a background thread named "async-io" the first time an `Async` or `Timer` is used, and that thread acts as a fallback reactor, so `smol::Timer::after` completes even under futures' `block_on`. It cannot complete I/O or timer types that expect their own runtime's reactor to be running in the current context. Those fail in a runtime-specific way, often a panic at creation. ## The split made visible in smol smol is a thin crate that re-exports smaller ones, so its source shows the parts by name: | piece | crate re-exported by smol | role | |---|---|---| | `Executor`, `LocalExecutor`, `Task` | `async-executor` | executor: queues and polls tasks | | `Async<T>`, `Timer`, `block_on` | `async-io` | reactor (through the `polling` crate) plus a `block_on` that processes I/O events while idle | | `unblock`, `Unblock` | `blocking` | a thread pool for blocking calls | | `future`, `stream`, `io`, `prelude` | `futures-lite` | combinators and traits | Tokio, by contrast, bundles its scheduler, I/O driver and timer driver into one runtime value; how those are configured is covered with Tokio itself. ## A complete executor in std alone Because the contract is just `poll` plus `Waker`, an executor without a reactor fits in a few lines of std using the `std::task::Wake` trait: see this question's code example. It runs any future whose wake-ups come from somewhere real. If you hand it a future that waits on a socket nobody is watching, it parks forever, which is exactly the missing-reactor failure in its plainest form. ## Why the distinction matters in practice - **Debugging a hang**: a future that never completes under a minimal executor usually means nothing will ever call its waker, often because its reactor is not running. - **Choosing a runtime**: a CLI that only needs one HTTP response can use a small executor plus a library that brings its own reactor; a server wants an executor and reactor tuned together. - **Writing libraries**: code that only combines futures, channels and the `futures` traits needs no reactor and works under any executor; code that opens sockets ties itself to whichever reactor owns them. - **Reading a runtime's documentation**: when a crate says its types "must be used within" a runtime, it is telling you which reactor has to be running, not which executor is allowed to poll. ## A worked trace Suppose a task awaits a read on a socket that has no data yet: 1. the executor polls the task, and the read future asks the reactor to watch the socket, storing the task's `Waker`; 2. the read future returns `Pending`, so the task returns `Pending` and the executor moves on to other work or sleeps; 3. data arrives; the reactor's wait call returns the event and it calls `wake` on the stored waker; 4. the executor re-queues the task, polls it again, and this time the read completes.
- Why does a future awaiting `smol::Timer::after` complete even when it is driven by `futures::executor::block_on`?smol's timers come from the `async-io` crate, which spawns a background thread named "async-io" the first time an `Async` or `Timer` is used. That thread runs the reactor as a fallback whenever no `async_io::block_on` is processing events, so it fires the timer and calls the stored waker, which unparks the thread inside futures' `block_on`.
- What happens if a hand-written executor parks after `Poll::Pending` but the future never stored its waker anywhere?The thread parks and nothing ever unparks it, so the program hangs. The executor relies on the future's promise to arrange a wake-up before returning `Pending`; a future that breaks that promise, or depends on a reactor that is not running, leaves every executor waiting forever.
- Saying the Waker is the part that reads data from the socket.
- Believing futures::executor::block_on includes an I/O reactor.
- Thinking an executor busy-loops calling poll while a future is pending.
- Claiming the Future trait itself differs between runtimes.
- Confusing the reactor with the thread pool used for blocking calls.