rust / expert
Snippet
Yielding Async Tasks via Custom Waker Wakeups
This snippet implements cooperative multitasking by creating a custom future that yields control back to the async executor once before waking itself up, preventing a single long-running task from starving others.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use std::future::Future;use std::pin::Pin;use std::task::{Context, Poll};struct YieldOnce {yielded: bool,}impl Future for YieldOnce {type Output = ();fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {if self.yielded {Poll::Ready(())} else {self.yielded = true;cx.waker().wake_by_ref();Poll::Pending}}}async fn execute_cooperative_task() -> i32 {let mut sum = 0;for i in 0..10 {sum += i;if i % 3 == 0 {YieldOnce { yielded: false }.await;}}sum}
Breakdown
1
struct YieldOnce
Holds state tracking whether the future has already yielded execution to the executor loop.
2
cx.waker().wake_by_ref()
Schedules the current task to be rescheduled for execution in the executor's next iteration.
3
Poll::Pending
Signals to the executor that the task is temporarily blocked, prompting a context switch to other tasks.
4
YieldOnce { yielded: false }.await
Suspends the execution flow at cooperative points, allowing interleaved task execution.