Sub topic 17
Runtimes and why blocking calls stall other tasks
This chapter assumes you know how Future, poll, Waker, and a basic executor like block_on work, and that you have used threads and Arc. It explains what a runtime adds on top of an executor, and why a blocking call inside a task can freeze unrelated work.
What a runtime adds to an executor
The block_on you built earlier runs one future on one thread. A real async runtime, such as Tokio or async-std, is an executor plus several other parts:
- A task scheduler that holds many spawned futures and decides which one to poll next.
- One or more worker threads that do the polling.
- A reactor, which asks the operating system (through epoll, kqueue, or IOCP) which sockets and files are ready, and then calls
wakeon the matching wakers. - Timers, so a future such as
sleepcan ask to be woken at a given time. - Often a separate thread pool for work that must block.
The standard library gives you Future, Waker, and Context. It does not give you a reactor or a scheduler. That is why you pick a runtime crate.
Tasks versus futures
A future is a value. A task is a future that the runtime owns and polls on its own. You turn a future into a task by spawning it. The runtime wraps the future with some bookkeeping, usually a state flag and a handle for the result, and puts it in a queue.
Tokio's spawn has this shape:
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,The 'static bound exists because the task can outlive the function that spawned it. The Send bound exists because a multi-threaded runtime may poll the task on any worker thread. The previous chapter on Send explained why a future that holds a non-Send value across an .await fails this bound.
The rule: poll must return quickly
Cooperative scheduling means a task gives up the thread only when poll returns. In a well-behaved future, poll does a little work and returns Pending when it cannot go on. The runtime then polls something else on that thread.
Nothing can force a task to return. The runtime has no way to interrupt poll in the middle of a function. If a task runs a long computation or a blocking call without ever reaching an .await that returns Pending, the worker thread is occupied until it finishes.
With threads, the operating system preempts a thread that runs too long. With async tasks, nothing preempts them.
A blocking call stalls its worker thread
Consider this program. It uses the Tokio runtime with one worker thread, so the effect is easy to see.
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..5 {
println!("tick {i} at {:?}", start.elapsed());
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
let blocker = tokio::spawn(async {
// Blocks the whole thread for one second.
std::thread::sleep(Duration::from_secs(1));
println!("blocker done");
});
let _ = tokio::join!(ticker, blocker);
}You might expect the ticks to print every 100 ms, with "blocker done" appearing after one second. What happens depends on which task is polled first. If the blocker is polled before the ticker's second tick, std::thread::sleep holds the only worker thread for a full second. The ticker is ready to run, its timer has fired, and its waker has been called, but nobody is free to poll it. The ticks arrive late and in a burst.
Replace the blocking call with tokio::time::sleep(Duration::from_secs(1)).await and the problem disappears. That version returns Pending immediately and registers a timer with the runtime. The thread is free to poll the ticker meanwhile.
The difference is where the waiting happens:
| Call | What the thread does while waiting | Other tasks on that thread |
|---|---|---|
| `std::thread::sleep(d)` | The OS suspends the thread | Cannot run |
| `tokio::time::sleep(d).await` | Returns `Pending`, thread polls other tasks | Keep running |
| A tight CPU loop | Runs code the whole time | Cannot run |
Multi-threaded runtimes make this less obvious
Tokio's default runtime uses several worker threads, usually one per CPU core. A single blocking task then stalls only one worker. The rest of the program keeps running, so the bug can hide during development.
It shows up under load. If as many tasks block as there are workers, the runtime has no thread left to poll anything. Timeouts fire late, connections time out, and the program looks hung. Often there is no panic and no error message, only high latency.
What counts as blocking
Anything that keeps the thread busy for a noticeable time without returning to the runtime is blocking. A common rule of thumb is that a task should not go more than tens of microseconds to a few milliseconds between .await points. Typical offenders are:
std::thread::sleep.- Synchronous file and network I/O from
std::fsandstd::net. - Waiting on a
std::sync::Mutexthat another thread holds for a long time. std::sync::mpsc::Receiver::recv.- CPU-heavy work such as hashing, compression, parsing a huge document, or image processing.
- Calls into synchronous libraries, including some database drivers and FFI functions.
Holding a std::sync::Mutex guard across an .await is a separate problem, because the guard is not Send and the future then fails the Send bound. A short, non-awaiting critical section with a std::sync::Mutex is fine.
Fixing it: move blocking work off the async threads
You have three main options.
- Use the async version of the API, such as
tokio::fs,tokio::net,tokio::time::sleep, andtokio::sync::Mutex. This is the best choice when one exists. - Send the blocking work to a dedicated pool with
spawn_blocking. Tokio keeps a separate set of threads for this, so async workers stay free. - For long-running CPU work, use a separate thread or a CPU pool such as Rayon, and send the result back through a channel.
Here is spawn_blocking in use:
use std::time::Duration;
#[tokio::main]
async fn main() {
let handle = tokio::task::spawn_blocking(|| {
// Safe to block here: this runs on the blocking pool.
std::thread::sleep(Duration::from_secs(1));
42
});
let value = handle.await.unwrap();
println!("got {value}");
}spawn_blocking takes an ordinary closure, not a future. Awaiting the returned JoinHandle is a normal async wait, so the calling task returns Pending until the blocking pool finishes.
Two limits apply. The blocking pool has a maximum size (512 threads by default in Tokio), so unbounded blocking work still queues up. And a closure that is already running on a blocking thread cannot be cancelled by dropping the handle. The work continues until it finishes.
Yielding in long async loops
A loop can also hog a thread without any blocking call. For example, a task that processes a large in-memory queue and only awaits operations that are always ready never returns Pending.
async fn drain(items: Vec<u64>) -> u64 {
let mut total = 0;
for item in items {
total += expensive(item);
// Gives the scheduler a chance to poll other tasks.
tokio::task::yield_now().await;
}
total
}
fn expensive(n: u64) -> u64 {
(0..n % 1000).sum()
}yield_now returns Pending once, wakes itself, and so puts the task at the back of the queue. Calling it on every iteration costs scheduling overhead, so in practice you yield every N items. Tokio also has a cooperative budget that makes its own resources, such as channels and sockets, return Pending after many consecutive ready operations. That protects against some starvation, but it does not help with your own computation.
Choosing between the options
| Situation | Preferred approach |
|---|---|
| An async version of the API exists | Use it directly |
| A short blocking call from a sync library | `spawn_blocking` |
| Long CPU-bound work, such as a minute of compute | A dedicated thread or Rayon pool, with a channel for the result |
| A long async loop with no real waiting | `yield_now` every few iterations, or move it off the runtime |
| Program is entirely synchronous apart from one async call | Build a small runtime and call `block_on` at that boundary |
Calling block_on inside a runtime
Calling a runtime's block_on from inside one of its own tasks is the same mistake in another form. The worker thread waits for a future while the runtime needs that thread to drive the future. Tokio detects this and panics with a message that you cannot start a runtime from within a runtime. Other runtimes may deadlock instead.
To call async code from a blocking context that is running inside the runtime, use spawn_blocking and then Handle::current().block_on inside that closure, which is permitted on a blocking-pool thread.
Exercise
A service runs on a multi-threaded Tokio runtime with 4 worker threads. A handler calls std::fs::read_to_string on a large file inside an async fn. It works in testing, but under load, unrelated requests time out. Explain why, and give two fixes.
Show answer
std::fs::read_to_string blocks the worker thread until the read finishes. The task never returns Pending, so the runtime cannot poll other tasks on that thread. With enough concurrent requests, all 4 workers are blocked at once and no task can be polled, so unrelated requests time out. Fixes: use tokio::fs::read_to_string(...).await, which runs the read off the async workers, or wrap the call in tokio::task::spawn_blocking and await the handle.
Exercise
Why does tokio::time::sleep(d).await let other tasks run while std::thread::sleep(d) does not, in terms of poll?
Show answer
tokio::time::sleep returns a future whose poll registers a timer and the task's waker, then returns Poll::Pending, so the worker thread goes back to the scheduler and polls other tasks. When the timer fires, the waker is called and the task is polled again. std::thread::sleep is an ordinary function call that suspends the whole OS thread inside the current poll, so poll does not return and the thread cannot poll anything else.