Sub topic 13
Keeping the runtime responsive: spawn_blocking
This chapter assumes you can start a Tokio runtime with #[tokio::main], spawn tasks, and know that a future only makes progress when it is polled. You should also be comfortable with closures and Send + 'static bounds.
Why blocking code hurts
Tokio runs many tasks on a small pool of worker threads. A task gives up its thread only when it reaches an .await that is not ready. Code that never reaches an .await keeps the thread for as long as it runs. Examples are a long computation, std::thread::sleep, a blocking file read, or a synchronous library call.
If every worker thread is stuck this way, no other task can be polled. Timers fire late, sockets go unread, and the program looks frozen. The compiler will not warn you about this.
The blocking thread pool
Tokio keeps a second, separate pool of threads for blocking work. tokio::task::spawn_blocking takes a closure, runs it on that pool, and returns a JoinHandle. Awaiting the handle suspends only your task. The async worker threads stay free.
#[tokio::main]
async fn main() {
let sum = tokio::task::spawn_blocking(|| (1..=1_000_000u64).sum::<u64>())
.await
.unwrap();
println!("sum = {sum}");
}The closure must be Send + 'static, and so must its return value. This is the same bound that tokio::spawn imposes. Move owned data into the closure instead of borrowing it.
The unwrap handles the JoinError that appears if the closure panicked. The closure's own result is the Ok value.
What it does and does not do
- The pool grows on demand, up to 512 threads by default. Idle threads are released after a timeout.
- A closure that has started cannot be cancelled. Dropping the
JoinHandledetaches the work, and it runs to completion anyway. - The closure is plain synchronous code. You cannot use
.awaitinside it. - For heavy parallel CPU work, such as processing a large array on every core, a dedicated pool like
rayonis a better fit. The blocking pool is for occasional blocking calls.
Spotting the problem
A common symptom is a timer that fires much later than requested while the runtime is busy. If tasks stall under load, look for synchronous code in async functions. Typical culprits are std::fs, blocking database drivers, password hashing, and compression.
| Situation | Use |
|---|---|
| Waiting for time | `tokio::time::sleep` |
| Reading a socket | `tokio::net` types |
| Blocking library call | `spawn_blocking` |
| Long CPU computation | `spawn_blocking`, or `rayon` for parallel work |
Exercise
A task calls std::thread::sleep(Duration::from_secs(2)) on a current-thread runtime while other tasks are waiting on timers. What happens to those timers, and how do you fix it?
Show answer
The current-thread runtime has one thread, and the sleep holds it for two seconds. No other task can be polled, so the timers fire late. Replace the call with tokio::time::sleep(...).await. If the code is a blocking call that cannot be replaced, wrap it in tokio::task::spawn_blocking and await the handle.