Sub topic 7
Writing a Future by hand
This chapter assumes you know what Poll::Ready and Poll::Pending mean, and that a Waker is how a future asks to be polled again. It also assumes you can use Arc, Mutex, and thread::spawn. Here you will implement Future twice, then run both futures on a small executor.
The contract of `poll`
Every hand-written future has to meet the same rules:
pollruns when the executor calls it. It must not block the thread.- It returns
Poll::Ready(value)if the work is finished. - Otherwise it returns
Poll::Pending, and before returning it must arrange forcx.waker()to be woken later. If nothing will ever wake it, the task hangs forever. - After returning
Ready, the future may panic or misbehave if polled again. Executors do not poll a finished future.
The compiler cannot check the waker rule. It is the most common source of bugs in hand-written futures.
A future that wakes itself
The first future counts down and asks to be polled again each time it returns Pending:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct CountDown(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}self.0 -= 1 compiles because CountDown contains only a u32, so it is Unpin. For Unpin types, Pin<&mut Self> implements DerefMut, and you can mutate fields as if it were a plain &mut Self. Later chapters cover what changes when a type is not Unpin.
wake_by_ref before Pending is legal. It tells the executor to poll again soon, so this future behaves like a polite busy loop. It is fine for a demo, but a real future waits for an event instead.
A future that waits for an event
A real leaf future (one that waits on something outside the executor) needs three pieces:
- Shared state that the event source and the future both see.
- A place to store the latest waker.
- An event source that sets the state and calls
wake.
Delay uses a helper thread as its event source. The thread sleeps, marks the state as done, and wakes whichever task last polled the future:
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::thread;
use std::time::Duration;
struct Shared {
done: bool,
waker: Option<Waker>,
}
struct Delay {
shared: Arc<Mutex<Shared>>,
}
impl Delay {
fn new(dur: Duration) -> Self {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let for_thread = Arc::clone(&shared);
thread::spawn(move || {
thread::sleep(dur);
let mut s = for_thread.lock().unwrap();
s.done = true;
if let Some(w) = s.waker.take() {
w.wake();
}
});
Delay { shared }
}
}
impl Future for Delay {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.shared.lock().unwrap();
if s.done {
return Poll::Ready(());
}
let stale = match &s.waker {
Some(w) => !w.will_wake(cx.waker()),
None => true,
};
if stale {
s.waker = Some(cx.waker().clone());
}
Poll::Pending
}
}Three details matter here.
The lock covers both the check and the store. poll reads done and stores the waker while holding the mutex. The timer thread sets done and takes the waker under the same mutex. If these steps were not atomic with respect to each other, the timer could fire between "not done yet" and "waker stored". Then nobody would wake the task. This is a lost wakeup.
The waker is replaced on every poll when needed. A task can move between executor threads, or be wrapped in a different combinator, between two polls. Its Context may then carry a different waker. Waking a stale waker would wake the wrong thing. will_wake lets you skip the clone when the waker is equivalent, but you must still replace it when it is not.
Delay is Unpin. Its only field is an Arc, so self.shared works through Pin with no unsafe.
The flow of one poll cycle
The diagram shows one full cycle for Delay, including the park and unpark that the executor performs.
Running both futures
To run them you need an executor. The block_on below is the one a later chapter builds step by step. This is the complete file, with all imports merged:
use std::future::Future;
use std::pin::{pin, Pin};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use std::time::Duration;
struct CountDown(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
struct Shared {
done: bool,
waker: Option<Waker>,
}
struct Delay {
shared: Arc<Mutex<Shared>>,
}
impl Delay {
fn new(dur: Duration) -> Self {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let for_thread = Arc::clone(&shared);
thread::spawn(move || {
thread::sleep(dur);
let mut s = for_thread.lock().unwrap();
s.done = true;
if let Some(w) = s.waker.take() {
w.wake();
}
});
Delay { shared }
}
}
impl Future for Delay {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.shared.lock().unwrap();
if s.done {
return Poll::Ready(());
}
let stale = match &s.waker {
Some(w) => !w.will_wake(cx.waker()),
None => true,
};
if stale {
s.waker = Some(cx.waker().clone());
}
Poll::Pending
}
}
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() {
println!("{}", block_on(CountDown(3)));
let msg = block_on(async {
Delay::new(Duration::from_millis(100)).await;
"slept"
});
println!("{msg}");
}It prints done, then slept after about 100 ms. The async block awaits a hand-written future exactly as it would await one from a library, because .await only needs the Future trait.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Return `Pending` without storing or calling a waker | The task hangs and the CPU stays idle | Store `cx.waker().clone()` or call `wake_by_ref` before returning |
| Store the waker only on the first poll | Occasional hangs when the task is polled with a different waker | Compare with `will_wake` and replace it when needed |
| Check state and store the waker without a shared lock | Rare lost wakeups | Make the check and the store atomic against the event source |
| Block inside `poll` (for example `thread::sleep`) | Other tasks on the same thread stall | Return `Pending` and let an event source wake you |
| Poll again after `Ready` | A panic, or a wrong value | Track completion yourself if your future can be polled again |
A spurious wakeup is also normal. The executor may poll you when nothing has changed. poll must therefore re-check its condition each time and return Pending again if needed. Both futures above already do this.
Exercise
Suppose you change Delay::poll so it never stores the waker and just returns Pending when done is false. The timer thread still sets done = true after 100 ms. What happens when you run it under block_on, and why?
Show answer
The program hangs. The first poll returns Pending, and block_on parks the thread. When the timer thread finishes, s.waker is None, so nothing calls wake and nothing unparks the executor thread. No further poll ever happens, so the Ready branch is never reached.
Exercise
In CountDown::poll, why does self.0 -= 1 compile without unsafe, and what would change if the struct also contained a PhantomPinned field?
Show answer
CountDown is Unpin, so Pin<&mut CountDown> implements DerefMut and gives ordinary mutable access to the fields. With a PhantomPinned field the type becomes !Unpin. DerefMut is no longer available, so the line would not compile. You would need unsafe { self.get_unchecked_mut() }, or a pin projection, to modify the field.