macro_rules! spawn_fair {
($future:expr) => { ... };
}Expand description
Cooperatively yields to the Tokio scheduler before spawning a new task, ensuring fair task scheduling especially under high load or on platforms like Windows where newly spawned tasks may not execute promptly.
This function should be used in cases where a tight loop repeatedly spawns tasks (e.g., after reading from a channel), to prevent starving previously scheduled tasks.
§Example
while let Some(msg) = rx.recv().await {
spawn_fair!(async move {
handle(msg).await;
});
}§Notes
- This is a drop-in replacement for
tokio::spawn. - On Windows, it inserts a short sleep after yielding to ensure fair scheduling.