A hand-written Rust Future, a Delay that polls a shared flag set by a timer thread, returns Poll::Pending without touching its Context, and block_on hangs; why, and what fixes it?
answer
- Pending carries an obligation
- who will call poll again?
- store the newest Waker
- flag and waker under one lock
basics
~20 sReturning Poll::Pending obliges the future to arrange a wake-up, and this Delay never stores cx.waker(), so nothing wakes the task and block_on never polls it again. Store a clone of the latest Waker beside the flag, under one lock, and wake it from the timer thread.
solid answer
~40 s`Poll::Pending` is a promise: std's docs say a function returning it *must* also ensure the current task is scheduled to be woken when progress can be made. The broken `Delay` checks the flag, sees `false`, and returns `Pending` without touching `cx`. The timer thread later sets the flag, but nobody calls `wake`, so an executor such as `futures::executor::block_on`, which parks its thread until woken, sleeps forever. The fix: keep the flag and an `Option<Waker>` in one `Arc<Mutex<..>>`; in `poll`, if not done, store `cx.waker().clone()`, replacing any older one, and return `Pending`; in the timer thread, set the flag and `take()` and `wake()` the stored waker. Checking the flag and storing the waker under the same lock closes the lost-wakeup race.
code
rust · 31 linesuse std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::{thread, time::Duration};
struct Shared { done: bool, waker: Option<Waker> }
struct Delay(Arc<Mutex<Shared>>);
impl Future for Delay {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut s = self.0.lock().unwrap();
if s.done { return Poll::Ready(()); }
s.waker = Some(cx.waker().clone()); // newest waker, same lock as the flag
Poll::Pending
}
}
fn main() {
let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));
let timer = Arc::clone(&shared);
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
let mut s = timer.lock().unwrap();
s.done = true;
if let Some(w) = s.waker.take() { w.wake(); }
});
futures::executor::block_on(Delay(shared));
println!("sensor interval elapsed");
}go deeper
Remember that a future returning Pending has to make sure someone will wake its task, or it will never be polled again.
Show how to clone cx.waker(), share it with the event source, and call wake when the event happens.
Diagnose the hang from first principles, then cover the newest-waker rule, the lost-wakeup race closed by one lock, and why a self-wake busy-polls.
Treat hand-written leaf futures as rare code that needs review against the waker contract and tests that poll them with a real executor.
## The obligation behind `Poll::Pending` In Rust a future makes progress only when something calls its `poll` method. The executor that owns the task decides when to do that, and an executor typically polls a pending task again only after its **`Waker`** has been woken; the `Future` docs say `poll` should not be called in a tight loop. That is why the standard library attaches a contract to the `Pending` variant: when a function returns `Poll::Pending`, it *must* also ensure that the current task is scheduled to be awoken when progress can be made. A future that wraps another future meets the contract by passing `cx` down. A **leaf future**, one written by hand around a flag, a timer or a device, has nobody to delegate to, so it must take the `Waker` from `cx.waker()` and hand it to whoever will learn that progress is possible. ## Why the broken `Delay` hangs The faulty version looks like this: ```rust fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> { if self.done.load(Ordering::Acquire) { Poll::Ready(()) } else { Poll::Pending } } ``` Trace it under `futures::executor::block_on`: 1. `block_on` polls `Delay`; the flag is still `false`, so it returns `Pending`. 2. `block_on` has been given no wake-up, so it parks its thread until the task's `Waker` is invoked. 3. The timer thread sets the flag 50 ms later and exits. It never calls `wake`, because it has no `Waker` to call. 4. The thread stays parked, and the program never prints `ready`. The future's logic is correct and the flag really is set; the program hangs only because no poll ever comes to observe it. An executor that happened to re-poll for other reasons, such as another future in the same task becoming ready, would make the bug intermittent, which is worse. ## The fix Share both the flag and the waker between the future and the timer thread: - **`poll`** locks the shared state. If `done`, it returns `Poll::Ready(())`. Otherwise it stores `cx.waker().clone()` in `waker` and returns `Poll::Pending`. - **the timer thread** locks the same state, sets `done = true`, then `take()`s the stored waker and calls `wake()` on it. The runnable example does exactly that and finishes after about 50 ms. ## Three details a senior gets right 1. **Keep the newest waker.** The `Future` docs say that across several calls to `poll`, only the `Waker` from the most recent call should receive the wake-up; the async book adds that a future can move to a different task between polls. Overwrite the stored waker on every poll rather than storing it once. `Waker::will_wake` reports, on a best-effort basis, whether two wakers wake the same task, and `Waker`'s `clone_from` uses it to skip a needless clone. 2. **Check and register under one lock.** If the flag were read outside the lock and the waker stored after, the timer could set the flag and find no waker in between, and the wake would be lost. One `Mutex` around both fields, or a purpose-built cell such as the futures crate's `futures::task::AtomicWaker`, makes check-then-register atomic with respect to set-then-wake. 3. **Do not paper over it with a self-wake.** Calling `cx.waker().wake_by_ref()` before every `Pending` does make the program finish, but the executor then re-polls in a loop and burns a core while it waits. That shortcut is only reasonable for a future that yields deliberately once. | Variant | Outcome under `block_on` | |---|---| | returns `Pending`, never stores the waker | hangs forever | | stores the waker only on the first poll | works here; can miss the wake if the future moves to another task | | stores the newest waker under the flag's lock | correct | | calls `wake_by_ref()` before every `Pending` | finishes, but busy-polls | ## Smaller tools for the same job - **`std::future::poll_fn`** (stable since 1.64) builds a future from a closure that receives `&mut Context`, which is handy for a one-off leaf without a named type. The waker contract is unchanged. - **`Waker::noop()`** (stable since 1.85) is for tests that poll by hand and do not need a wake-up; using it in production code discards every wake. - Executors build their wakers from **`std::task::Wake`** or a `RawWaker`; that side belongs to the lesson on runtimes. The `Waker` you receive is `Send` and `Sync`, so storing it in state shared with another thread is allowed.
- Why is storing the waker only on the first poll not enough?A future can be moved to a different task between polls, for example when a combinator or select loop hands it on, and that task has a different Waker. The Future docs say only the Waker from the most recent poll should be woken, so the stored one must be refreshed on each poll.
- Is it a bug to call wake while still holding the Mutex?Not a correctness bug here: wake only tells the executor to schedule the task. Waking after releasing the lock is slightly better because the re-poll then never contends for it, but correctness depends on setting the flag and taking the waker under the same lock.
- Could the Delay just call std::thread::sleep inside poll?It would return the right answer, but poll should return quickly and not block. Sleeping inside poll stalls the executor thread and every other task scheduled on it for the whole delay.
- Returning Pending is enough; the executor polls again on its own shortly after.
- Storing the waker once on the first poll is always enough.
- The hang means the timer thread never set the flag.
- Calling wake_by_ref before every Pending is the proper fix.
- A Waker cannot be sent to another thread, so the timer cannot wake the task.