Sub topic 12
Keeping the runtime responsive: blocking code
This chapter assumes you can write async fn, use .await, and start tasks with tokio::spawn. It also assumes you know that Tokio runs many tasks on a small pool of worker threads.
Why blocking hurts
An async task only gives up its thread at an .await point. Between two .awaits, the task holds the worker thread and nothing can interrupt it. If that stretch of code takes a long time, the worker can't poll any other task.
Two kinds of code cause this:
- Blocking calls, such as
std::thread::sleep,std::fs::read, or a synchronous database driver. - Long CPU-bound loops, such as hashing, compression, or parsing a large file.
The symptoms are timers that fire late, slow responses, and in the worst case a stalled program. The compiler won't warn you, because the code is valid Rust.
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
tokio::spawn(async {
// Blocks the only worker thread for two seconds.
std::thread::sleep(Duration::from_secs(2));
});
// This timer is due after 100 ms, but it can't run until the
// blocked task finishes.
tokio::time::sleep(Duration::from_millis(100)).await;
println!("woke up late");
}Replacing std::thread::sleep with tokio::time::sleep(...).await fixes it, because the task then yields the thread while it waits.
Moving work with spawn_blocking
tokio::task::spawn_blocking runs a closure on a separate pool of threads meant for blocking work. It returns a JoinHandle, which you .await like any other task handle.
#[tokio::main]
async fn main() {
let sum = tokio::task::spawn_blocking(|| (1..=1_000_000u64).sum::<u64>())
.await
.unwrap();
println!("{sum}");
}The .unwrap() handles the Result from the handle. It is an Err if the closure panicked.
Common errors
- Blocking inside
async fnwithout noticing. Calls into synchronous libraries are the usual cause. Check what a dependency does before calling it from a task. - Holding a
std::sync::Mutexguard across an.await. The guard blocks other threads, and the future also stops beingSend. Usetokio::sync::Mutexif you must hold the lock across an await, or release the guard first. - Expecting
spawn_blockingto be cancellable. Once the closure starts, dropping the handle doesn't stop it. It runs to the end. - Using
spawn_blockingfor endless loops. The blocking pool has a large but finite size, so long-lived work can use it all up. Give that work its ownstd::thread.
Exercise
A task calls std::thread::sleep(Duration::from_secs(1)) inside an async fn on a runtime with one worker thread. What happens to other tasks, and how do you fix it?
Show answer
No other task can run for that second, because the sleep holds the only worker thread and never reaches an .await. Replace it with tokio::time::sleep(Duration::from_secs(1)).await, which yields the thread. If the blocking call can't be replaced, run it with tokio::task::spawn_blocking.
Exercise
You call spawn_blocking for a long computation, then drop its JoinHandle. Does the computation stop?
Show answer
No. The closure keeps running on its blocking thread until it returns. Dropping the handle only means you can no longer get the result. To stop it early, the closure itself must check a flag such as an AtomicBool and return.