Sub topic 1
Futures do nothing until polled
A Rust future is a value that describes work. Creating one does not start the work. This chapter explains what that means, who starts the work, and why it matters for cancellation, timeouts, and select!. Later chapters build on it.
Prerequisites
This chapter assumes you already know:
- Basic Rust: ownership, borrowing, traits, and the
Droptrait. - The
async/awaitsyntax and the idea of aFuture. - The Tokio basics:
#[tokio::main]andtokio::spawn.
The examples use Tokio with the full feature set. A minimal Cargo.toml entry is tokio = { version = "1", features = ["full"] }.
An async function returns a value, it does not run
Calling an async fn runs none of its body. It builds a value that holds the arguments and the function's state, and it returns that value immediately.
async fn greet() {
println!("hello from greet");
}
#[tokio::main]
async fn main() {
let fut = greet();
println!("future created");
fut.await;
println!("future finished");
}The output is:
future created
hello from greet
future finished"hello from greet" prints after "future created". The call greet() only built the future. The body ran when .await drove the future.
If you drop fut without awaiting it, the message never prints. The compiler warns about this, because Future is marked #[must_use]. The warning reads "unused implementer of Future that must be used". Treat it as an error. A forgotten .await is the most common source of "my code didn't run" bugs.
The Future trait and poll
A future is any type that implements this trait, shown here in simplified form:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> {
Ready(T),
Pending,
}poll is the only way to make progress. Each call does as much work as it can without blocking, then returns one of two results:
Poll::Ready(value)means the future is finished and here is its output.Poll::Pendingmeans the future cannot continue yet, for example because it waits for a timer or a socket.
Nothing inside a future runs on its own. No thread belongs to it, and no background process advances it. Code in the future executes only while some caller is inside poll.
Writing a future by hand
A hand-written future makes the mechanism visible. This one needs several polls before it finishes, and it counts them.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct Countdown {
remaining: u32,
polls: u32,
}
impl Future for Countdown {
type Output = u32;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
self.polls += 1;
if self.remaining == 0 {
Poll::Ready(self.polls)
} else {
self.remaining -= 1;
// Ask the runtime to poll us again.
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
let fut = Countdown { remaining: 3, polls: 0 };
println!("created, nothing has run yet");
let polls = fut.await;
println!("ready after {polls} polls");
}The program prints ready after 4 polls: three Pending results, then one Ready.
The cx.waker().wake_by_ref() call matters. When a future returns Pending, the runtime stops polling it until something wakes it. The waker is the handle that tells the runtime "poll this task again". Real futures hand the waker to a timer, a socket, or a channel, and that resource wakes the task when something changes. If a future returns Pending and never arranges a wake-up, the task hangs forever. Here the future wakes itself, so the runtime polls it again right away.
Who calls poll
Your code rarely calls poll directly. The chain of callers looks like this:
- The runtime (the executor) polls each top-level task. A top-level task is the future passed to
block_onortokio::spawn. - That task's
asyncbody polls the future behind each.await. - Those futures poll their own inner futures, down to a leaf future such as a timer or a socket read.
.await is therefore not a blocking call. It means: poll this future now. If it is Ready, continue with the value. If it is Pending, return Pending to my own caller, so the whole task pauses and the runtime can run something else.
Laziness has consequences
Sequential awaits do not overlap
Because a future only runs while it is being polled, a.await; b.await; finishes a before b is even polled. To run futures at the same time, a single task must poll both. tokio::join! does this.
use std::time::{Duration, Instant};
use tokio::time::sleep;
async fn step() {
sleep(Duration::from_millis(100)).await;
}
#[tokio::main]
async fn main() {
let start = Instant::now();
step().await;
step().await;
println!("sequential: {} ms", start.elapsed().as_millis());
let start = Instant::now();
tokio::join!(step(), step());
println!("joined: {} ms", start.elapsed().as_millis());
}The sequential version takes about 200 ms. The joined version takes about 100 ms, because join! polls both futures each time the task is polled.
Spawning is the exception to "nothing runs"
tokio::spawn hands a future to the runtime as a new top-level task. The runtime polls it without anyone awaiting it, so it makes progress on its own.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let _handle = tokio::spawn(async {
println!("spawned task is running");
});
// Give the runtime a chance to poll the spawned task.
sleep(Duration::from_millis(50)).await;
println!("main done");
}The spawned task prints even though nobody awaits _handle. The laziness rule still holds. The future runs because the runtime is polling it. Dropping a JoinHandle does not cancel the task. It only detaches you from the result.
Some state starts at creation, not at the first poll
Laziness means the body does not run, but a few constructors do work eagerly. tokio::time::sleep is the important case. It computes its deadline when you call it, not when it is first polled.
use std::time::{Duration, Instant};
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let early = sleep(Duration::from_millis(200)); // deadline is fixed here
sleep(Duration::from_millis(150)).await;
let start = Instant::now();
early.await;
println!("waited another {} ms", start.elapsed().as_millis());
}This prints roughly 50, not 200. The 200 ms clock started when sleep was called, so only about 50 ms remained when the program awaited it. Inside an async fn or async block, sleep(...) written in the body runs at first poll, so the deadline starts then. The difference appears only when you build the future early and await it later.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Compiler warning "unused implementer of `Future`" | You called an async function and discarded the result | Add `.await`, or pass the future to `spawn` or `join!` |
| Work seems to run one step at a time | Futures awaited one after another | Use `join!`, `select!`, or `spawn` to run them concurrently |
| Task hangs and never finishes | A hand-written future returned `Pending` without arranging a wake-up | Store the waker and wake it, or call `wake_by_ref` |
| A timer fires earlier than expected | The `Sleep` was created long before it was awaited | Create the future at the point where you want the clock to start |
| Side effect missing after an early return | The future holding it was dropped before being polled | Check whether the future was ever awaited or spawned |
Why this matters for cancellation
A future makes progress only while someone polls it, so stopping the polling stops the work. A future that is never polled again does nothing further, and dropping it also releases everything it holds. This is the basis of cancellation in async Rust. The next chapters show where a task can actually stop (await points), what dropping does to a half-finished future, and how timeout and select! use that behavior.
Summary
- An
async fncall returns a future and runs none of the body. - A future advances only inside
poll, which returnsReadyorPending. - The runtime polls top-level tasks, and
.awaitpolls the nested futures. - A
Pendingfuture must arrange a wake-up through the waker, or its task hangs. join!andspawngive you concurrency. Sequential.awaitdoes not.- Some constructors, such as
sleep, begin their state at creation.
Exercise
This program prints "start" and "end" but never prints "working". Why, and what are two ways to fix it? async fn work() { println!("working"); } #[tokio::main] async fn main() { println!("start"); let _fut = work(); println!("end"); }
Show answer
work() only builds a future, and nothing polls it, so the body never runs. The binding _fut is dropped at the end of main without ever being polled. Fix 1: await it, with work().await;. Fix 2: spawn it with tokio::spawn(work()); and give the runtime time to poll it, for example by awaiting the returned JoinHandle.
Exercise
A hand-written future's poll returns Poll::Pending on its first call and never touches the Context. What happens when you await it inside a Tokio task, and why?
Show answer
The task hangs forever. Returning Pending tells the runtime to stop polling the task until its waker is called. This future never stored or called the waker, so nothing wakes the task and the runtime never polls it again. The fix is to call cx.waker().wake_by_ref() before returning Pending, or to hand the waker to the resource that will signal readiness.