From bb2815ae23031c0ffd90e34166ceb95908c15682 Mon Sep 17 00:00:00 2001 From: Dongpo Liu Date: Tue, 7 Jul 2026 15:40:18 +0200 Subject: [PATCH] task: explain why `yield_now` defers its waker (#8254) Since #5223, `yield_now` does not wake the task immediately. Instead, the waker is handed to the scheduler via `context::defer`, which wakes it only after running out of ready tasks and polling the IO/timer driver. Add a comment explaining this, as the reasoning is not obvious from the bare `context::defer` call. --- tokio/src/task/yield_now.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tokio/src/task/yield_now.rs b/tokio/src/task/yield_now.rs index a58e85ee7..ea09804ad 100644 --- a/tokio/src/task/yield_now.rs +++ b/tokio/src/task/yield_now.rs @@ -46,6 +46,12 @@ pub async fn yield_now() { yielded = true; + // Don't wake the task immediately, as that would push it right back + // onto the run queue and it could be polled again before other tasks + // or the IO/timer driver get a chance to run. Instead, hand the waker + // to the scheduler, which wakes deferred tasks only after it has run + // out of ready tasks and polled the driver. When polled from outside + // a Tokio runtime, the waker is woken immediately. context::defer(cx.waker()); Poll::Pending