Blog

Part 26 · Async Rust: Build a Tiny Executor by Hand, Then Use tokio

An async fn returns a future that does nothing until something polls it. We build that something by hand with the standard library, a waker and a run queue, and then run the same program on tokio.

Threads from Part 23 give each piece of work its own stack and let the operating system switch between them. Async Rust does a similar job inside your program. Many small tasks share a few threads, and a task steps aside whenever it has to wait. Nothing in the language runs those tasks for you. That job belongs to a library called an executor.

So we’ll build one. First, with the standard library only: what an async fn returns, the Future trait, a future written by hand, a block_on that sleeps until it’s woken, and a small executor with a run queue and a timer. Then we’ll write the same program on tokio, the executor most Rust projects use, and match each piece of tokio to the piece we wrote. It builds on closures from Part 16, Box and Rc from Part 20, trait objects from Part 21, and Arc, Mutex and channels from Part 24. Every program here was run on Rust 1.95 (and tokio 1.54.1), and its output is pasted from the run.

Try this first

greet is an async fn. main calls it. What does this print?

async fn greet() -> u32 {
    println!("hello from greet");
    7
}

fn main() {
    let _future = greet();
    println!("made the future");
    println!("end of main");
}

It prints:

made the future
end of main

hello from greet never appears. Calling greet() didn’t run its body. It built a value that can run the body later, and then main dropped that value without asking it to. In Rust, that value is called a future, and a future does nothing until something polls it.

That’s the opposite of JavaScript, where calling an async function starts it at once. In Rust, an async function is lazy. Somebody has to drive it.

Polling a future by hand

Let’s drive it ourselves. Three tools from std are enough:

use std::pin::pin;
use std::task::{Context, Waker};

async fn greet() -> u32 {
    println!("hello from greet");
    7
}

fn main() {
    let mut future = pin!(greet());
    println!("made the future");

    let mut cx = Context::from_waker(Waker::noop());
    let result = future.as_mut().poll(&mut cx);
    println!("poll returned {result:?}");
}

It prints:

made the future
hello from greet
poll returned Ready(7)

The body ran when we called poll, and not before. poll returned Ready(7): the future finished, and 7 is its answer. We’ll explain pin!, Context and Waker in the next two sections. For now: pin! fixes the future in one place in memory, and Waker::noop() is a waker that does nothing when it’s used.

We didn’t need use std::future::Future to call poll. In edition 2024, the Future trait is in the prelude, the set of names every Rust file gets for free.

The Future trait

Here is the trait, as the standard library defines it (comments removed):

pub trait Future {
    type Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

pub enum Poll<T> {
    Ready(T),
    Pending,
}

Every part of it does one job:

  • Output is the type of the answer. For greet, it’s u32. Output is an associated type, the same idea as Item on Iterator (Part 22).
  • poll asks the future to make progress. It returns Poll::Ready(answer) when it has finished, or Poll::Pending when it’s waiting for something, like a timer or a network reply.
  • cx: &mut Context carries a waker. cx.waker() returns a &Waker.
  • A Waker is a handle with one useful method, wake(). It means “poll me again, I can make progress now”.

The deal between a future and whoever polls it is short:

  1. If poll returns Pending, the future must make sure that somebody calls wake() on that waker when it’s worth polling again.
  2. The poller doesn’t need to poll a pending future again until it’s woken, so it can do other work, or sleep. (An extra poll is allowed. It just wastes time, and the future returns Pending again.)

That deal is the whole of async Rust. A future never blocks a thread while it waits. It returns Pending at once, and the waker brings it back.

self: Pin<&mut Self> is a &mut self with an extra promise attached. We’ll get to it after we’ve seen why it’s needed.

A future written by hand

greet was ready on its first poll. Let’s write a future that isn’t. CountDown returns Pending a few times, and each time it wakes itself straight away, so the poller knows to come back:

use std::pin::{Pin, pin};
use std::task::{Context, Poll, Waker};

struct CountDown {
    left: u32,
}

impl Future for CountDown {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.left == 0 {
            return Poll::Ready("liftoff");
        }
        println!("  countdown: {} left", self.left);
        self.left -= 1;
        cx.waker().wake_by_ref();
        Poll::Pending
    }
}

fn main() {
    let mut future = pin!(CountDown { left: 3 });
    let mut cx = Context::from_waker(Waker::noop());
    let mut polls = 0;
    loop {
        polls += 1;
        println!("poll {polls}");
        if let Poll::Ready(word) = future.as_mut().poll(&mut cx) {
            println!("ready: {word}");
            break;
        }
    }
}

It prints:

poll 1
  countdown: 3 left
poll 2
  countdown: 2 left
poll 3
  countdown: 1 left
poll 4
ready: liftoff

wake_by_ref() is wake() without giving up the waker. Before it returns Pending, CountDown keeps its side of the deal: it calls the waker.

But look at main. Our waker does nothing, so main can’t tell when to poll again, and it just polls in a loop. That’s fine for a countdown. For a future that waits a whole second for a timer, this loop would spin the CPU at 100% for that second. We need a waker that does something.

block_on: sleep until woken

The simplest useful executor runs one future on the current thread. When the future is pending, the thread goes to sleep. When the waker is called, the thread wakes up and polls again.

Part 23 used thread::park, which puts a thread to sleep until another call, unpark, wakes it. That’s exactly what we need. The standard library’s Wake trait turns any Arc<T> into a Waker, if T says what wake does:

use std::pin::{Pin, pin};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

struct ThreadWaker {
    thread: Thread,
}

impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        println!("  (wake: unpark the main thread)");
        self.thread.unpark();
    }
}

fn block_on<F: Future>(future: F) -> F::Output {
    let mut future = pin!(future);
    let waker = Waker::from(Arc::new(ThreadWaker {
        thread: thread::current(),
    }));
    let mut cx = Context::from_waker(&waker);
    loop {
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(value) => return value,
            Poll::Pending => thread::park(),
        }
    }
}

struct CountDown {
    left: u32,
}

impl Future for CountDown {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.left == 0 {
            return Poll::Ready("liftoff");
        }
        println!("  countdown: {} left", self.left);
        self.left -= 1;
        cx.waker().wake_by_ref();
        Poll::Pending
    }
}

async fn launch() -> u32 {
    println!("launch: start");
    let word = CountDown { left: 2 }.await;
    println!("launch: {word}");
    let again = CountDown { left: 1 }.await;
    println!("launch: {again} again");
    2
}

fn main() {
    let launches = block_on(launch());
    println!("main got {launches}");
}

It prints:

launch: start
  countdown: 2 left
  (wake: unpark the main thread)
  countdown: 1 left
  (wake: unpark the main thread)
launch: liftoff
  countdown: 1 left
  (wake: unpark the main thread)
launch: liftoff again
main got 2

A few things to notice:

  • block_on is generic over any F: Future. It returns F::Output, so block_on(launch()) gives back the u32 that launch returns.
  • The waker is an Arc<ThreadWaker> turned into a Waker with Waker::from. The Arc is there because a waker can be cloned and sent to other threads, and every copy must reach the same thread.
  • Here, wake runs before park, because CountDown wakes itself inside poll. That’s safe. unpark leaves a token, and a park that finds the token returns at once. park can also return for no reason at all (the docs call it a spurious wakeup), which is why block_on polls again in a loop instead of trusting it.
  • launch awaits two futures, one after the other. The three wakes came from inside them, and launch itself never touched the waker. .await passed our cx down to each inner future.

What .await turns into

How did launch pass its cx down? The compiler turns every async fn into a type that implements Future. That type is an enum with one variant for each place the function can pause, and each variant holds the local variables that are still needed after that point. .await becomes “poll the inner future; if it’s pending, return Pending too”.

We can write that enum ourselves for a short launch and check that it behaves the same:

use std::pin::{Pin, pin};
use std::task::{Context, Poll, Waker};

struct CountDown {
    left: u32,
}

impl Future for CountDown {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.left == 0 {
            return Poll::Ready("liftoff");
        }
        self.left -= 1;
        cx.waker().wake_by_ref();
        Poll::Pending
    }
}

// What we write:
async fn launch() -> u32 {
    println!("launch: start");
    let word = CountDown { left: 2 }.await;
    println!("launch: {word}");
    2
}

// Roughly what the compiler writes for us:
enum Launch {
    Start,
    Waiting(CountDown),
    Done,
}

impl Future for Launch {
    type Output = u32;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
        loop {
            match &mut *self {
                Launch::Start => {
                    println!("launch: start");
                    *self = Launch::Waiting(CountDown { left: 2 });
                }
                Launch::Waiting(countdown) => match Pin::new(countdown).poll(cx) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(word) => {
                        println!("launch: {word}");
                        *self = Launch::Done;
                        return Poll::Ready(2);
                    }
                },
                Launch::Done => panic!("polled after it finished"),
            }
        }
    }
}

fn run<F: Future>(future: F) -> F::Output {
    let mut future = pin!(future);
    let mut cx = Context::from_waker(Waker::noop());
    let mut polls = 1;
    loop {
        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
            println!("ready after {polls} polls");
            return value;
        }
        polls += 1;
    }
}

fn main() {
    println!("async fn  -> {}", run(launch()));
    println!("hand-made -> {}", run(Launch::Start));
}

It prints:

launch: start
launch: liftoff
ready after 3 polls
async fn  -> 2
launch: start
launch: liftoff
ready after 3 polls
hand-made -> 2

Same lines, same number of polls. The real enum the compiler makes is more careful than ours, and you never see it. But the idea is this one: an async function is a state machine, and each poll runs it from one pause point to the next. That’s why a future does nothing until it’s polled. Before the first poll, it’s just the Start variant, a value sitting in memory.

It’s also why async tasks are cheap. A thread needs its own stack, usually megabytes of address space. A task is just this enum, sized for the variables it keeps across an .await.

Why Pin exists

Our hand-made Launch keeps only a CountDown across its pause. A real async function can keep a variable and a reference to that variable:

async fn first_word() {
    let text = String::from("hello world");
    let first = &text[..5]; // points into text
    some_timer().await;     // pause: text and first are both saved in the enum
    println!("{first}");
}

Both text and first live inside the same enum value, and first points at a field next to it. If anyone moved that enum to another address after it started, first would still point at the old address. Part 8 showed what that kind of dangling reference does, and why Rust won’t allow one.

Pin is how Rust prevents that move. A Pin<&mut Fut> is a &mut Fut that promises the future will stay where it is until it’s dropped. poll takes self: Pin<&mut Self>, so you can only poll a future that has been pinned. You pin one in two ways:

  • pin!(future) pins it on the stack, in the current function. We used this in block_on.
  • Box::pin(future) puts it on the heap and pins it there. The box can move around freely, because the future inside doesn’t. We’ll use this for a list of tasks.

Most types never hold a reference to themselves, and they implement the auto trait Unpin, which says “pinning me changes nothing”. CountDown is Unpin, which is why its poll could just write self.left -= 1, and why Launch could poll it with a plain Pin::new. The futures that async fn creates are not Unpin. That’s all you need about Pin for now. You meet it when you write futures by hand, and an executor library handles it the rest of the time.

Many tasks: a tiny executor

block_on runs one future. The point of async is to run many on the same thread: while one task waits, another runs. For that we need three more pieces:

  • tasks: futures the executor owns, stored as Pin<Box<dyn Future<Output = ()> + Send>>. That’s the trait object from Part 21, boxed and pinned, so tasks of different types can share one Vec;
  • a run queue: the ids of the tasks that are ready to be polled. We use an mpsc channel from Part 24;
  • a waker per task whose wake puts that task’s id back on the queue.

And a future that really waits: Sleep, a timer. On its first poll, it starts a helper thread that sleeps, then calls the waker. Here’s the whole program. It’s the longest in the series so far; the notes after it take it piece by piece.

use std::pin::Pin;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread;
use std::time::Duration;

// ----- a timer future, driven by a helper thread -----

#[derive(Default)]
struct SleepState {
    done: bool,
    waker: Option<Waker>,
}

struct Sleep {
    ms: u64,
    started: bool,
    shared: Arc<Mutex<SleepState>>,
}

fn sleep(ms: u64) -> Sleep {
    Sleep {
        ms,
        started: false,
        shared: Arc::default(),
    }
}

impl Future for Sleep {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let mut state = self.shared.lock().unwrap();
        if state.done {
            return Poll::Ready(());
        }
        state.waker = Some(cx.waker().clone());
        drop(state);

        if !self.started {
            self.started = true;
            let shared = Arc::clone(&self.shared);
            let ms = self.ms;
            thread::spawn(move || {
                thread::sleep(Duration::from_millis(ms));
                let mut state = shared.lock().unwrap();
                state.done = true;
                let waker = state.waker.take();
                drop(state);
                if let Some(waker) = waker {
                    waker.wake();
                }
            });
        }
        Poll::Pending
    }
}

// ----- the executor: a run queue of task ids -----

type Task = Pin<Box<dyn Future<Output = ()> + Send>>;

struct TaskWaker {
    id: usize,
    queue: Sender<usize>,
}

impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        // If the executor has already finished, nobody is listening. That's fine.
        let _ = self.queue.send(self.id);
    }
}

struct Executor {
    tasks: Vec<Option<(&'static str, Task)>>,
    queue: Sender<usize>,
    ready: Receiver<usize>,
}

impl Executor {
    fn new() -> Executor {
        let (queue, ready) = mpsc::channel();
        Executor {
            tasks: Vec::new(),
            queue,
            ready,
        }
    }

    fn spawn(&mut self, name: &'static str, future: impl Future<Output = ()> + Send + 'static) {
        let id = self.tasks.len();
        self.tasks.push(Some((name, Box::pin(future))));
        self.queue.send(id).unwrap();
    }

    fn run(mut self) {
        let mut left = self.tasks.len();
        while left > 0 {
            let id = self.ready.recv().unwrap();
            let Some((name, task)) = &mut self.tasks[id] else {
                continue; // woken after it finished: nothing to do
            };
            let name = *name;
            let waker = Waker::from(Arc::new(TaskWaker {
                id,
                queue: self.queue.clone(),
            }));
            let mut cx = Context::from_waker(&waker);
            println!("executor: poll {name}");
            match task.as_mut().poll(&mut cx) {
                Poll::Pending => println!("executor: {name} is pending"),
                Poll::Ready(()) => {
                    println!("executor: {name} is done");
                    self.tasks[id] = None;
                    left -= 1;
                }
            }
        }
    }
}

fn main() {
    let mut executor = Executor::new();
    executor.spawn("A", async {
        println!("  A: start, sleep 50 ms");
        sleep(50).await;
        println!("  A: woke up");
    });
    executor.spawn("B", async {
        println!("  B: nothing to wait for");
    });
    executor.run();
}

It prints:

executor: poll A
  A: start, sleep 50 ms
executor: A is pending
executor: poll B
  B: nothing to wait for
executor: B is done
executor: poll A
  A: woke up
executor: A is done

Piece by piece:

  • Sleep shares a SleepState with its helper thread through Arc<Mutex<...>>, as in Part 24. Every poll stores a clone of the current waker, so the helper always wakes whoever polled last. The helper thread starts on the first poll, not in sleep(), so Sleep is lazy like every other future. When the time is up, the helper sets done, takes the waker out, unlocks, and calls wake().
  • spawn boxes and pins the future, stores it under the next id, and puts that id on the queue. Nothing runs yet.
  • run takes ids off the queue one at a time and polls that task with a waker that knows its id. A finished task’s slot becomes None. An id that arrives for a finished task is skipped, because a waker may fire late. When no tasks are left, run returns.
  • recv() blocks when the queue is empty. That’s where our executor sleeps: after B is done, the main thread waits inside recv until the timer thread sends A’s id.

The output doesn’t depend on timing, and that’s by design. The queue starts as [A, B]. A’s poll starts the timer. Even if the timer fired instantly, A’s id would join the queue behind B’s. So the executor always polls A, then B, then A. We ran it 20 times to be sure, and got the same nine lines every time.

The + Send on Task isn’t needed by our one-thread executor. We kept it because tokio’s spawn asks for it, and the error you get without it is one of the worked examples below.

Here’s the same run as a picture:

run queue executor timer thread poll() done waiting A B sleep 50 ms fired! A waker A: Pending B: Ready A: Ready B A wake(A): A's id goes back in the queue run queue: A, B run queue: B · waiting: A run queue: empty · waiting: A · done: B run queue: A · done: B run queue: empty · done: A, B spawn puts tasks A and B in the run queue poll A: Pending. A gives its waker to the timer and waits poll B: Ready. B is done; with an empty queue, the executor sleeps the timer fires and calls wake(): A goes back in the queue poll A: Ready. Both tasks are done, so run() returns

The executor only polls tasks whose ids are in the run queue. A pending task leaves the queue, and its waker is the only way back in.

Here are those steps in words, in case the animation doesn’t play for you:

  1. spawn puts tasks A and B in the run queue. Nothing has run yet.
  2. The executor polls A. A starts its 50 ms timer, gives the timer thread its waker, and returns Pending. A leaves the queue and waits.
  3. The executor polls B. B has nothing to wait for and returns Ready, so it’s done. The queue is now empty, so the executor sleeps inside recv().
  4. The timer fires and calls wake() on A’s waker. That sends A’s id back into the run queue, and the executor wakes up.
  5. The executor polls A again. Its timer is done, so A returns Ready. Both tasks are done, and run returns.

Explain it like I’m ten

Picture a small restaurant with one waiter. The waiter takes table A’s order and gives it to the kitchen. The waiter doesn’t stand at the kitchen door waiting for the food. They go to table B, who only wants a glass of water, and bring it right away. Then the waiter sits down, because nobody needs anything.

When A’s food is ready, the kitchen rings a bell. The waiter gets up, picks up the plate and takes it to table A. One waiter served two tables without wasting a minute standing around.

The precise version

The waiter is the executor, and it runs on one thread. Each table is a task: a future the executor owns. “Taking an order” is a call to poll. If the task can’t finish yet, poll returns Pending, and the task hands a Waker to whatever it’s waiting on, here the timer thread. The executor only polls tasks whose ids are in its run queue, and when the queue is empty, it blocks. The timer calls wake(), which puts the task’s id back in the queue, and the executor polls it again. A task that’s waiting costs no CPU time at all.

Where the analogy breaks: a waiter decides on their own to check a table. An executor never polls a pending task just to check. If nothing calls wake(), the task is never polled again, and it hangs forever. Also, the kitchen in our program is a whole thread per timer. Real executors share one timer system among thousands of tasks, and the operating system tells them when network data arrives.

The same program on tokio

Our executor works, but it’s a toy. It has one thread, a whole helper thread per timer, and no networking. Real programs use a runtime crate, and the most common one is tokio. The tokio half of this part is a cargo project in rust/examples/26-async-tokio/. Its Cargo.toml pins tokio to one exact version, and turns on only the features we use:

[dependencies]
tokio = { version = "=1.54.1", features = ["rt-multi-thread", "macros", "time", "sync"] }

Here’s the start of src/main.rs, with the same two tasks our executor ran:

use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::time::sleep;

#[tokio::main]
async fn main() {
    spawn_and_await().await;
    join_two().await;
    race_with_select().await;
    workers_and_a_channel().await;
}

// The same two tasks as our hand-built executor ran.
async fn spawn_and_await() {
    let a = tokio::spawn(async {
        sleep(Duration::from_millis(50)).await;
        "A woke up"
    });
    let b = tokio::spawn(async { "B had nothing to wait for" });

    // A JoinHandle is a future too. Awaiting it gives the task's result.
    println!("spawn: {}", b.await.unwrap());
    println!("spawn: {}", a.await.unwrap());
}

What’s new compared with ours:

  • #[tokio::main] lets main be async. The macro rewrites it into a normal main that starts a runtime and calls the runtime’s block_on on your async body. It’s our block_on, built for real.
  • tokio::spawn is our Executor::spawn. The task starts running in the background straight away, without waiting for anyone to await it.
  • It returns a JoinHandle, which is itself a future. Awaiting it gives Ok(answer), or an Err if the task panicked or was cancelled. That’s why we unwrap it, the same as join on a thread in Part 23.
  • tokio::time::sleep is our Sleep. It returns a future that’s Pending until the time is up.

We print B’s answer first and A’s second, because we await them in that order. Each line comes from main, so the output doesn’t depend on which task finished first.

join! and select! run several futures inside one task:

async fn slow_double(n: u64) -> u64 {
    sleep(Duration::from_millis(200)).await;
    n * 2
}

// join! polls both futures in this task, and waits for both.
async fn join_two() {
    let start = Instant::now();
    let (x, y) = tokio::join!(slow_double(2), slow_double(5));
    let together = start.elapsed() < Duration::from_millis(400);
    println!("join!: {x} and {y}, both sleeps at once: {together}");
}

// select! waits for the first branch to finish and drops the other.
async fn race_with_select() {
    tokio::select! {
        _ = sleep(Duration::from_secs(10)) => println!("select!: the slow job won"),
        _ = sleep(Duration::from_millis(50)) => println!("select!: gave up after 50 ms"),
    }
}

join! finished in about 200 ms, not 400, because both sleeps were waiting at the same time. We print true or false instead of the time, so the output is the same on every run. select! is a race: the 50 ms branch wins, and the 10 second sleep is dropped. Dropping a future is how you cancel it in Rust. It never gets polled again, so its code after the current pause point never runs.

Last, a channel. tokio::sync::mpsc works like the std channel from Part 24, except that send and recv are async, so a task that waits for a message gives the thread back:

// Three tasks send results to one receiver.
async fn workers_and_a_channel() {
    let (tx, mut rx) = mpsc::channel(8);
    for id in 1..=3 {
        let tx = tx.clone();
        tokio::spawn(async move {
            sleep(Duration::from_millis(10 * id)).await;
            tx.send(format!("worker {id} done")).await.unwrap();
        });
    }
    drop(tx); // otherwise rx.recv() would wait for our copy forever

    let mut results = Vec::new();
    while let Some(message) = rx.recv().await {
        results.push(message);
    }
    results.sort();
    println!("mpsc: {results:?}");
}

The 8 is the channel’s capacity: tokio’s channel is bounded, like sync_channel in Part 24. We sort the results because tasks on different threads may finish in any order. cargo run prints:

spawn: B had nothing to wait for
spawn: A woke up
join!: 4 and 10, both sleeps at once: true
select!: gave up after 50 ms
mpsc: ["worker 1 done", "worker 2 done", "worker 3 done"]

Which piece of tokio did we build?

Job Our version tokio
Run a future to the end on this thread block_on the runtime’s block_on, which #[tokio::main] calls for you
Start a task Executor::spawn tokio::spawn, which returns a JoinHandle
Pick the next task to poll an mpsc run queue of task ids the scheduler: a run queue per worker thread, and idle threads steal work from busy ones
Wait for time to pass a helper thread per Sleep one timer driver per runtime, shared by all its timers
Tell the executor a task can go on TaskWaker, made into a Waker with Wake the same std::task::Waker type, built by tokio
Threads that poll tasks one one per CPU core, by default, with #[tokio::main]

The last two rows matter most. Future, Poll, Context and Waker come from std, not from tokio. That’s why the futures you write, like CountDown, work on any runtime. And since tokio polls tasks on several threads, a task can move between threads at any .await. That’s why tokio::spawn needs Send.

Never block inside async code

An async task must return Pending while it waits. If it calls something that blocks, like std::thread::sleep, a lock held for a long time or a heavy calculation, it keeps the thread busy, and no other task can use that thread. The second file in the project, src/bin/blocking.rs, shows it on a runtime with one thread:

#[tokio::main(flavor = "current_thread")]
async fn main() {
    // Wrong: std::thread::sleep blocks the only thread the runtime has.
    tokio::spawn(async {
        std::thread::sleep(Duration::from_millis(300));
    });
    let start = Instant::now();
    sleep(Duration::from_millis(50)).await;
    let late = start.elapsed() >= Duration::from_millis(300);
    println!("std::thread::sleep in a task: our 50 ms nap took 300 ms or more: {late}");

    // Right: tokio's sleep gives the thread back while it waits.
    tokio::spawn(async {
        sleep(Duration::from_millis(300)).await;
    });
    let start = Instant::now();
    sleep(Duration::from_millis(50)).await;
    let late = start.elapsed() >= Duration::from_millis(300);
    println!("tokio::time::sleep in a task: our 50 ms nap took 300 ms or more: {late}");
}

cargo run --bin blocking prints:

std::thread::sleep in a task: our 50 ms nap took 300 ms or more: true
tokio::time::sleep in a task: our 50 ms nap took 300 ms or more: false

main asked for a 50 ms nap. While it slept, the runtime ran the spawned task, and std::thread::sleep held the only thread for 300 ms. main‘s 50 ms were up long before that, but nobody could poll main until the thread came back. In our restaurant, the waiter stood at the kitchen door. On the default multi-thread runtime, the same bug only stalls one worker, so it often passes your tests and shows up as slow requests under load.

When you must call blocking code from a task, tokio has tokio::task::spawn_blocking. It runs a closure on a separate pool of threads meant for blocking work, and gives you a JoinHandle to await.

When not to use async

Async helps when a program spends most of its time waiting, with many waits at once: a server with ten thousand open connections, or a client that sends a hundred requests and waits for them all. A thread per connection needs a stack each. A task needs only its state machine, which is usually much smaller.

It doesn’t help with these:

  • CPU-bound work. Resizing images or adding up a billion numbers never waits, so there’s nothing to overlap. Use threads, the way Part 23 split a sum into four chunks. (The rayon crate does this well, but it isn’t part of std.)
  • A few connections. A program that talks to three servers is simpler with three threads, and it’s just as fast. Part 30’s key-value server uses plain threads, because it serves a handful of clients at a time.
  • Small tools. Async adds a runtime, a dependency and longer compile errors. If nothing in your program waits on many things at once, you don’t need it.

Worked example: polling a future that isn’t pinned

Earlier, Launch polled its CountDown with Pin::new(&mut countdown). Let’s do the same with the future from an async fn:

use std::pin::Pin;
use std::task::{Context, Waker};

async fn greet() -> u32 {
    println!("hello from greet");
    7
}

fn main() {
    let mut future = greet();
    let mut cx = Context::from_waker(Waker::noop());
    let result = Pin::new(&mut future).poll(&mut cx);
    println!("poll returned {result:?}");
}

It prints:

error[E0277]: `{async fn body of greet()}` cannot be unpinned
...
  12 |     let result = Pin::new(&mut future).poll(&mut cx);
     |                  -------- ^^^^^^^^^^^ within `impl Future<Output = u32>`, the trait `Unpin` is not implemented for `{async fn body of greet()}`
...
     = note: consider using the `pin!` macro
             consider using `Box::pin` if you need to access the pinned value outside of the current scope

Read it in three steps:

  1. {async fn body of greet()} is the compiler’s name for the state machine it made from greet. You can’t write that type yourself, so the error also calls it impl Future<Output = u32>.
  2. Pin::new only accepts types that are Unpin, types for which pinning makes no difference. The async state machine might hold references into itself, so it isn’t Unpin.
  3. The note names both fixes from the section on Pin: pin! to pin it on the stack, or Box::pin to pin it on the heap. Our second program used pin!.

Worked example: a task that isn’t Send

Here’s a toy spawn with the same bound as tokio’s. It runs the future on a new thread, which is exactly why it needs Send:

use std::future::ready;
use std::pin::pin;
use std::rc::Rc;
use std::task::{Context, Waker};
use std::thread::{self, JoinHandle};

// A toy spawn: run the future on a new thread.
fn spawn<F>(future: F) -> JoinHandle<()>
where
    F: Future<Output = ()> + Send + 'static,
{
    thread::spawn(move || {
        let mut future = pin!(future);
        let mut cx = Context::from_waker(Waker::noop());
        while future.as_mut().poll(&mut cx).is_pending() {}
    })
}

fn main() {
    let task = spawn(async {
        let name = Rc::new(String::from("A"));
        ready(()).await;
        println!("task {name} done");
    });
    task.join().unwrap();
}

It prints:

error: future cannot be sent between threads safely
...
   | |______^ future created by async block is not `Send`
...
note: future is not `Send` as this value is used across an await
  --> src/main.rs:22:19
   |
21 |         let name = Rc::new(String::from("A"));
   |             ---- has type `Rc<String>` which is not `Send`
22 |         ready(()).await;
   |                   ^^^^^ await occurs here, with `name` maybe used later

std::future::ready(()) is a future that’s ready on its first poll. It stands in for any real .await.

This error has no code, and it’s one you’ll meet as soon as you use tokio. The note explains it. name is an Rc, which isn’t Send (Part 23). It’s still alive at the .await, so it has to be saved inside the state machine. That makes the whole future not Send, and spawn refuses it.

There are two fixes. Use Arc instead of Rc, which is what we do here. Or make sure the Rc is dropped before the .await, for example by using it inside a { } block that ends first.

use std::future::ready;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Waker};
use std::thread::{self, JoinHandle};

// A toy spawn: run the future on a new thread.
fn spawn<F>(future: F) -> JoinHandle<()>
where
    F: Future<Output = ()> + Send + 'static,
{
    thread::spawn(move || {
        let mut future = pin!(future);
        let mut cx = Context::from_waker(Waker::noop());
        while future.as_mut().poll(&mut cx).is_pending() {}
    })
}

fn main() {
    let task = spawn(async {
        let name = Arc::new(String::from("A"));
        ready(()).await;
        println!("task {name} done");
    });
    task.join().unwrap();
}

It prints:

task A done

Worked example: a future that forgets to wake

The most common bug in a hand-written future is returning Pending without arranging a wake. Nothing crashes. The program just stops. To show it without hanging the page, this block_on_for gives up if nobody wakes the future within a time limit. TwoStep is ready on its second poll, and a flag decides whether it calls the waker:

use std::pin::{Pin, pin};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use std::time::{Duration, Instant};

struct FlagWaker {
    thread: Thread,
    woken: AtomicBool,
}

impl Wake for FlagWaker {
    fn wake(self: Arc<Self>) {
        self.woken.store(true, Ordering::SeqCst);
        self.thread.unpark();
    }
}

// block_on, but it gives up if nobody wakes the future within `limit`.
fn block_on_for<F: Future>(limit: Duration, future: F) -> Option<F::Output> {
    let mut future = pin!(future);
    let flag = Arc::new(FlagWaker {
        thread: thread::current(),
        woken: AtomicBool::new(false),
    });
    let waker = Waker::from(Arc::clone(&flag));
    let mut cx = Context::from_waker(&waker);
    loop {
        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
            return Some(value);
        }
        let start = Instant::now();
        while !flag.woken.swap(false, Ordering::SeqCst) {
            if start.elapsed() >= limit {
                return None;
            }
            thread::park_timeout(limit);
        }
    }
}

struct TwoStep {
    polls: u32,
    remember_to_wake: bool,
}

impl Future for TwoStep {
    type Output = u32;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
        self.polls += 1;
        if self.polls == 2 {
            return Poll::Ready(self.polls);
        }
        if self.remember_to_wake {
            cx.waker().wake_by_ref();
        }
        Poll::Pending
    }
}

fn main() {
    let limit = Duration::from_millis(200);
    for remember_to_wake in [false, true] {
        let step = TwoStep {
            polls: 0,
            remember_to_wake,
        };
        match block_on_for(limit, step) {
            Some(polls) => println!("wake = {remember_to_wake}: ready after {polls} polls"),
            None => println!("wake = {remember_to_wake}: stuck, nobody woke it"),
        }
    }
}

It prints:

wake = false: stuck, nobody woke it
wake = true: ready after 2 polls

The first TwoStep would have been ready on its very next poll. It never got one. The executor did its job: it waited for a wake that never came. The woken flag is there because park_timeout can return early for no reason, and we only want to poll again after a real wake().

Real executors have no time limit, so in a real program this bug looks like a request that never finishes. When a hand-written future hangs, check every path that returns Pending. Each one must store the waker somewhere that will call it, or call it itself.

Tips and traps

  • A future you never await does nothing. Calling an async fn without .await builds a future and drops it. Rust warns unused implementer of Future that must be used. Read that warning as an error.
  • Blocking inside a task. std::thread::sleep, a long loop or a slow file read inside async code stalls every task on that thread. Use tokio::time::sleep, or move the work to spawn_blocking.
  • “future cannot be sent between threads safely”. Something that isn’t Send, often an Rc or a MutexGuard, is alive across an .await. Drop it before the .await, or use Arc.
  • Pending without a wake. A hand-written future that returns Pending must store cx.waker() somewhere that will wake it, or the task hangs with no error. Store the waker from the latest poll, because a task can be polled with a different waker each time.
  • Dropping a JoinHandle doesn’t stop the task. The task keeps running in the background. Dropping a plain future, as select! does, cancels it.
  • #[tokio::main] needs features. Without the macros feature, the attribute doesn’t exist, and the default multi-thread runtime also needs rt-multi-thread. If cargo build says something in tokio can’t be found, check the feature list first. Turn on only the features you use, as our Cargo.toml does.

A future does nothing until it’s polled, and a pending future is polled again only when its waker is called.

Exercises

Exercise 1. Without running it, what does chores print when we poll it, and what does the compiler warn about?

async fn wash() {
    println!("washing");
}

async fn chores() {
    wash();
    println!("chores done");
}

Exercise 2. Write a future YieldNow that returns Pending once, waking itself, and then Ready(()). Use it to make two tasks take turns on a small executor like ours. Task A should print A1, A2, A3 and task B B1, B2, B3, and the output should be A1 B1 A2 B2 A3 B3, one per line.

Exercise 3. CountDown { left: 2 } needs 3 polls. How many polls does this need, with the run function from the state machine section? Guess first.

async fn twice() {
    CountDown { left: 2 }.await;
    CountDown { left: 3 }.await;
}
Answers

1. It prints only chores done. wash() builds a future and drops it without polling it, so washing never appears. The compiler warns:

warning: unused implementer of `Future` that must be used
 --> src/main.rs:9:5
  |
9 |     wash();
  |     ^^^^^^
  |
  = note: futures do nothing unless you `.await` or poll them

Add .await to fix it:

use std::pin::pin;
use std::task::{Context, Poll, Waker};

async fn wash() {
    println!("washing");
}

async fn chores() {
    wash().await;
    println!("chores done");
}

fn main() {
    let mut future = pin!(chores());
    let mut cx = Context::from_waker(Waker::noop());
    if let Poll::Ready(()) = future.as_mut().poll(&mut cx) {
        println!("ready");
    }
}

It prints:

washing
chores done
ready

2. YieldNow wakes itself, so its task’s id goes to the back of the run queue, behind the other task. That’s what makes them take turns. tokio has the same future, called tokio::task::yield_now.

use std::pin::Pin;
use std::sync::Arc;
use std::sync::mpsc::{self, Sender};
use std::task::{Context, Poll, Wake, Waker};

struct YieldNow {
    yielded: bool,
}

impl Future for YieldNow {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        if self.yielded {
            return Poll::Ready(());
        }
        self.yielded = true;
        cx.waker().wake_by_ref(); // back of the queue, not forgotten
        Poll::Pending
    }
}

fn yield_now() -> YieldNow {
    YieldNow { yielded: false }
}

type Task = Pin<Box<dyn Future<Output = ()> + Send>>;

struct TaskWaker {
    id: usize,
    queue: Sender<usize>,
}

impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        let _ = self.queue.send(self.id);
    }
}

fn run(futures: Vec<Task>) {
    let (queue, ready) = mpsc::channel();
    let mut tasks: Vec<Option<Task>> = futures.into_iter().map(Some).collect();
    for id in 0..tasks.len() {
        queue.send(id).unwrap();
    }
    let mut left = tasks.len();
    while left > 0 {
        let id = ready.recv().unwrap();
        let Some(task) = &mut tasks[id] else {
            continue;
        };
        let waker = Waker::from(Arc::new(TaskWaker {
            id,
            queue: queue.clone(),
        }));
        let mut cx = Context::from_waker(&waker);
        if task.as_mut().poll(&mut cx).is_ready() {
            tasks[id] = None;
            left -= 1;
        }
    }
}

async fn count(name: &'static str) {
    for i in 1..=3 {
        println!("{name}{i}");
        yield_now().await;
    }
}

fn main() {
    run(vec![Box::pin(count("A")), Box::pin(count("B"))]);
}

It prints:

A1
B1
A2
B2
A3
B3

3. Six, not seven. The first CountDown is pending on polls 1 and 2. On poll 3 it’s ready, and the state machine goes straight on to the second CountDown in the same poll, which is pending on polls 3, 4 and 5. Poll 6 finishes it.

use std::pin::{Pin, pin};
use std::task::{Context, Poll, Waker};

struct CountDown {
    left: u32,
}

impl Future for CountDown {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.left == 0 {
            return Poll::Ready("liftoff");
        }
        self.left -= 1;
        cx.waker().wake_by_ref();
        Poll::Pending
    }
}

async fn twice() {
    CountDown { left: 2 }.await;
    CountDown { left: 3 }.await;
}

fn run<F: Future>(future: F) -> F::Output {
    let mut future = pin!(future);
    let mut cx = Context::from_waker(Waker::noop());
    let mut polls = 1;
    loop {
        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
            println!("ready after {polls} polls");
            return value;
        }
        polls += 1;
    }
}

fn main() {
    run(twice());
}

It prints:

ready after 6 polls

What’s next

A future is an enum, a task is a boxed future, and an Option<&T> is somehow the same size as a &T. In Part 27, we’ll look at how Rust lays values out in memory: size_of, alignment, padding, and why some types cost nothing at all.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.