Sub topic 12
Why blocking code ignores your timeout
This chapter assumes you know how timeout and select! cancel a future by dropping it. It covers the case where that mechanism cannot act.
Cancellation needs the future to yield
A future is cancelled only when something drops it. timeout can drop it only after the future returns Pending to the executor. If the code inside the future occupies the thread without reaching an .await that yields, the timer is never checked.
The timer and your code share the same thread. While your code holds it, nothing else on that task can run.
Seeing the delay
This program asks for a 100 ms limit but blocks for 500 ms first.
use std::time::{Duration, Instant};
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let start = Instant::now();
let work = async {
std::thread::sleep(Duration::from_millis(500)); // blocks the thread
sleep(Duration::from_secs(5)).await;
};
let result = timeout(Duration::from_millis(100), work).await;
println!("timed out: {}, after {:?}", result.is_err(), start.elapsed());
}It reports a timeout after about 500 ms, not 100 ms. If the blocking call were the last thing in the future, with no .await after it, the future would finish on its first poll. timeout would then return Ok, even though the work took longer than the limit.
Blocking also hurts other tasks. On a runtime worker thread, a blocked call stops every task scheduled on that worker. A current-thread runtime has only one worker, so it stops everything.
Moving blocking work off the runtime
Use tokio::task::spawn_blocking for synchronous work such as file parsing, hashing, or a blocking client library. It runs the closure on a separate thread pool. The returned JoinHandle is a normal future, so timeout works on it.
use std::time::Duration;
use tokio::{task::spawn_blocking, time::timeout};
#[tokio::main]
async fn main() {
let handle = spawn_blocking(|| {
std::thread::sleep(Duration::from_millis(500));
42
});
match timeout(Duration::from_millis(100), handle).await {
Ok(joined) => println!("result: {}", joined.unwrap()),
Err(_) => println!("gave up waiting"),
}
}The timeout now fires after 100 ms. Only the wait is cancelled, though. The closure keeps running on its pool thread until it returns, and JoinHandle::abort cannot stop a blocking task that has already started. When the runtime shuts down, it waits for running blocking tasks.
Making blocking work stoppable
Blocking code must stop itself. Share a flag and check it between steps.
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::Duration;
fn main() {
let stop = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&stop);
let worker = std::thread::spawn(move || {
let mut steps = 0u32;
while !flag.load(Ordering::Relaxed) {
steps += 1;
std::thread::sleep(Duration::from_millis(10));
}
steps
});
std::thread::sleep(Duration::from_millis(55));
stop.store(true, Ordering::Relaxed);
println!("worker stopped after {} steps", worker.join().unwrap());
}In a spawn_blocking closure, use the same pattern. You can also use CancellationToken::is_cancelled(), which is a plain synchronous check.
CPU-heavy async code
A long loop with no .await inside an async fn has the same problem. If it must stay async, add tokio::task::yield_now().await every so often. That gives the executor a chance to run the timer and drop the future. For heavy computation, spawn_blocking is usually the better fit.
Quick reference
| Situation | Effect on timeout | Fix |
|---|---|---|
| `std::thread::sleep` in async code | Fires late or never | Use `tokio::time::sleep` |
| Blocking library call | Fires late, stalls other tasks | `spawn_blocking` |
| Long CPU loop in async code | Fires late | `yield_now().await` or `spawn_blocking` |
| Running `spawn_blocking` closure | Wait is cancelled, work continues | Check a flag or token inside |
Exercise
A handler wraps async { std::thread::sleep(Duration::from_secs(3)); } in timeout(Duration::from_secs(1), ...). What does timeout return, and why?
Show answer
It returns Ok(()) after about 3 seconds. The future has no await point that yields, so it finishes on its first poll and holds the thread for the whole 3 seconds. timeout never gets a chance to drop it. Using tokio::time::sleep(...).await would give Err(Elapsed) after 1 second.