From 60c50045c6a527bd55e7499b66b54db11e103f92 Mon Sep 17 00:00:00 2001 From: Rodrigo Rejala Date: Sat, 11 Apr 2026 11:21:43 -0300 Subject: [PATCH] fix: handle race condition in Delay future waker (ch02) --- async-book/src/ch02-the-future-trait.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/async-book/src/ch02-the-future-trait.md b/async-book/src/ch02-the-future-trait.md index aa5797d..1436dfb 100644 --- a/async-book/src/ch02-the-future-trait.md +++ b/async-book/src/ch02-the-future-trait.md @@ -108,12 +108,12 @@ impl Future for Delay { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { - // Check if already completed + // Check if already completed before storing waker if *self.completed.lock().unwrap() { return Poll::Ready(()); } - // Store the waker so the background thread can wake us + // Store the waker - executor may pass a new one on each poll *self.waker_stored.lock().unwrap() = Some(cx.waker().clone()); // Start the background timer on first poll @@ -134,6 +134,11 @@ impl Future for Delay { }); } + // Double-check completion after storing waker (handles race condition) + if *self.completed.lock().unwrap() { + return Poll::Ready(()); + } + Poll::Pending // Not done yet } }