Explanation
What just happened
Both tasks ran on one thread. std::thread::sleep doesn’t .await: it put the whole thread to sleep, so the ready ticker had nowhere to run. tick 2 came only after slow call ends.
Try the what-if switch
- spawn_blocking: the sleep runs on a separate pool thread.
mainawaits it, freeing the runtime’s thread, so every tick prints beforeslow call ends. - sleep().await:
tokio::time::sleephands the thread back while it waits, so the ticker keeps ticking. - 2 workers: block vs await: A blocks one worker thread; B and C share the other, and C can move once A lets go.
Why
An async runtime runs many tasks on few threads. That only works if every task gives the thread back at its .awaits. One blocking call holds it for everyone.
Watch out
A long loop with no .await stalls the thread the same way.
Common questions
Why is std::thread::sleep bad in async code?
It blocks the whole thread, not just the task: in our run the ticker didn't tick once during the 100 ms sleep.
What does spawn_blocking do?
It runs the closure on a thread from Tokio's blocking pool and returns a future for the result. Awaiting it frees the async thread.
Should I use spawn_blocking or tokio::time::sleep?
To wait, use tokio::time::sleep(..).await. Use spawn_blocking for work that has to block.
Verified: this timeline matches a real program, checked in CI on Rust 1.99 with Tokio 1.54. How we verify. Unclear or wrong? Tell us