Articles / Rust

  • rust
  • async
  • futures
  • poll
  • waker
  • debugging

Why Your Async Rust Future Does Nothing Until Something Polls It

You call an async fn, nothing happens, and the compiler gives you a warning instead of an error. That is not a bug. Calling an async function does not run any of its body; it builds a value and hands it back.

async fn greet() {
    println!("hello");
}

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

This prints only made the future. "hello" never appears, because nothing ever asked the future to make progress.

A future is a value with a poll method

The Future trait has one method that matters: poll. It returns either Poll::Ready(value) or Poll::Pending. Nothing runs until someone calls poll, and the thing that calls it is an executor (tokio, async-std, or a loop you write yourself).

Here is the same function, polled by hand. Waker::noop() has been stable since Rust 1.85, and it gives us a waker that does nothing, which is fine for a future that never waits.

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

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

fn main() {
    let mut fut = pin!(greet());
    println!("built");

    let mut cx = Context::from_waker(Waker::noop());
    match fut.as_mut().poll(&mut cx) {
        Poll::Ready(v) => println!("ready with {v}"),
        Poll::Pending => println!("pending"),
    }
}

Output: built, then hello, then ready with 7. The body ran inside the poll call, on this thread, and nowhere else.

Why the compiler warns you

Futures are marked #[must_use], so the first example gets a warning along the lines of "futures do nothing unless you .await or poll them". If you bind it to _f you silence that warning, which is exactly how a dropped future ends up in real code.

The usual ways to lose one:

  • Calling do_thing() in a statement and forgetting .await.
  • Collecting futures into a Vec and never driving them.
  • Passing a future to a function that stores it but never polls it.
  • Binding it to _ or _f to quieten the lint.

Dropping an unpolled future is harmless, since it never started. It is just a struct holding its arguments.

Quick detour: what is the executor actually doing?

Hang on, this is smaller than it sounds. A minimal executor is about fifteen lines of standard library. It needs a waker that can wake the thread, and a loop that polls and then sleeps.

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 {
        if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
            return v;
        }
        thread::park();
    }
}

The loop polls, and if the answer is Pending it parks the thread. It only polls again after someone calls wake, which unparks it. That is the whole contract.

The waker is a promise

When a future returns Pending, it is promising to call the waker it was given once it can make progress. Break that promise and the executor will never poll it again. Here is a future that gets it right:

use std::pin::Pin;

struct YieldOnce(bool);

impl Future for YieldOnce {
    type Output = ();

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

fn main() {
    block_on(async {
        println!("before");
        YieldOnce(false).await;
        println!("after");
    });
}

It prints both lines and exits. Now delete the wake_by_ref() line. The program prints "before" and then hangs forever with no panic, no error and no CPU use, because the thread is parked and nobody will ever unpark it.

Spotting the lost wakeup

This is the classic symptom of a hand-written future that forgot its waker: a task that stops, uses no CPU, and never finishes. Real futures usually pass the waker down to something that stores it (a timer, a socket registration, a channel). If you write poll yourself, check these:

  1. Every path that returns Pending has arranged for the waker to be called later.
  2. The stored waker is refreshed on each poll, since the executor may hand you a different one.
  3. If you return Pending after polling an inner future, that inner future has registered the waker, not just your outer code.

The third one is the sneaky one. Polling an inner future and discarding its Pending to return your own means nobody is woken.

What this means for ordinary async code

With an executor like tokio, .await inside an async block just polls the inner future from within the outer one. Concurrency only appears when something polls several futures, such as tokio::spawn, join! or select!. A bare .await on one future after another is sequential, and a future you never await is a future that never ran.

The mental model that helps: an async fn is a constructor for a state machine, and poll is the only thing that moves it forward.