Does awaiting tokio::sleep(Duration::ZERO) yield back to the runtime or Poll::ready immediately?

By going through the source or docs I’m unable to find an answer for this question.

In general polling a future that immediately returns Poll::Ready doesn’t yield I believe. But I couldn’t find anything specific for sleep(Duration::ZERO).

3 Likes

tokio::time::sleep does not guarantee to yield to the executor unless it needs to sleep; for a sleep(Duration::ZERO), the current implementation will not yield (and similar applies to tokio::time:sleep_until with an Instant that's in the past).

As @theemathas points out, there's tokio::task::yield_now for a guaranteed yield, with all of the reasoning documented there around yielding and select! type combinators, plus runtime behaviour around selecting another task.

1 Like

Whatever the current implementation does, it's not guaranteed to yield. In fact, there have been requests to special case sleep(0) because it can end up sleeping for 1ms under some circumstances, as Tokio's timer only tracks timers down to the millisecond and ignores precision below that threshold.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.