Sub topic 17
Runtimes and why blocking calls stall other tasks
This chapter assumes you know how a future is polled, what a Waker does, and what a minimal block_on looks like. It builds on those ideas to show what a full runtime adds and what goes wrong when a task blocks.
What a runtime adds to an executor
Your block_on runs one future on one thread. A runtime such as Tokio is an executor plus the services futures depend on:
- A scheduler that holds many tasks and polls the ones that have been woken.
- A reactor that waits on the operating system for socket and timer events, then calls the matching wakers.
- A timer wheel for
sleepand timeouts. - A pool of threads for work that cannot be made async.
A task is a spawned future that the scheduler owns. A task only runs while the scheduler is inside its poll call. Nothing can interrupt it, so the scheduler gets the thread back only when poll returns Pending or Ready.
How blocking stalls other tasks
Async concurrency is cooperative. A task that calls a blocking function such as std::thread::sleep, a synchronous file read, or a long loop never returns from poll. The worker thread is stuck. Every other task assigned to that thread waits, even if its waker has already fired.
This example uses Tokio's single-threaded runtime, so the effect is easy to see. Add tokio = { version = "1", features = ["rt", "macros", "time"] } to Cargo.toml.
use std::time::{Duration, Instant};
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
let ticker = tokio::spawn(async move {
for i in 0..3 {
println!("tick {i} at {} ms", start.elapsed().as_millis());
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
let blocker = tokio::spawn(async {
std::thread::sleep(Duration::from_millis(500)); // blocks the thread
});
let _ = tokio::join!(ticker, blocker);
}The ticker should print at about 0, 100, and 200 ms. Instead, tick 1 appears after about 500 ms, because the blocker held the only thread.
Fixing it
Move blocking work off the async threads. Use spawn_blocking, which runs a closure on a separate thread pool and returns a future you can .await:
let blocker = tokio::task::spawn_blocking(|| {
std::thread::sleep(std::time::Duration::from_millis(500));
});You can also use the async version of the operation, such as tokio::time::sleep, when one exists. A multi-threaded runtime hides the problem for a while, because other worker threads keep running. If you block as many tasks as there are workers, everything stalls again.
Common errors
| Symptom | Likely cause |
|---|---|
| Timers fire late | A task is blocking a worker thread |
| Throughput collapses under load | Blocking calls inside `async fn` |
| Deadlock with a `std::sync::Mutex` | A guard is held across `.await` |
| Hang inside `block_on` | `block_on` called from inside a runtime thread |
Exercise
A task on a single-threaded runtime calls std::thread::sleep(Duration::from_secs(2)). Why does another task's tokio::time::sleep(Duration::from_millis(100)) finish late, even though its waker fires on time?
Show answer
The waker only marks the task as ready to run. Polling it needs the scheduler thread, and that thread is stuck inside the first task's poll call for two seconds. Cooperative scheduling cannot preempt it, so the second task is polled only after the blocking call returns.