Sub topic 6
Async timers and I/O
This chapter assumes you can write an async fn, use .await, and start a Tokio runtime with #[tokio::main]. It also assumes you have Tokio with the full feature enabled in Cargo.toml.
Why timers and I/O need async versions
std::thread::sleep and std::fs::read block the whole OS thread. On an async runtime, that thread may be driving many tasks, so every one of them stalls. Tokio provides replacements that return futures. When such a future isn't ready, it returns Pending and the thread moves on to other tasks.
How a timer wakes your task
A tokio::time::sleep future registers a deadline with the runtime's timer driver, then returns Pending. When the deadline passes, the driver calls the task's waker, and the executor polls the task again.
Repeating work with interval
sleep in a loop drifts, because each iteration adds the time the work took. interval schedules ticks against a fixed period instead. The first tick completes immediately.
use std::time::Duration;
use tokio::time::interval;
#[tokio::main]
async fn main() {
let mut ticker = interval(Duration::from_millis(100));
for i in 0..3 {
ticker.tick().await;
println!("tick {i}");
}
}Async file I/O
Tokio mirrors the standard library under tokio::fs, tokio::net, and tokio::io. Reading and writing go through the AsyncReadExt and AsyncWriteExt traits, which you must import to call methods like read_to_string and write_all.
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let path = std::env::temp_dir().join("async_demo.txt");
let mut file = File::create(&path).await?;
file.write_all(b"hello async").await?;
file.flush().await?;
let mut file = File::open(&path).await?;
let mut text = String::new();
file.read_to_string(&mut text).await?;
println!("{text}");
Ok(())
}Common errors
- Calling
std::thread::sleepinside an async function. It compiles, but it freezes the worker thread. - Forgetting
flush().awaiton atokio::fs::File. Writes run in the background, so data may not be on disk when you read it back. - Missing the
AsyncReadExtorAsyncWriteExtimport. The compiler then reports that the method doesn't exist. - Forgetting
.awaitonsleep(...). The future is created but never polled, so no delay happens.
| Blocking version | Async version |
|---|---|
| `std::thread::sleep` | `tokio::time::sleep` |
| `std::fs::read_to_string` | `tokio::fs::read_to_string` |
| `std::net::TcpStream` | `tokio::net::TcpStream` |
Exercise
A loop calls std::thread::sleep(Duration::from_secs(1)) inside an async function that runs on Tokio, and other tasks become unresponsive. Why does this happen, and what is the fix?
Show answer
std::thread::sleep blocks the OS thread, so the runtime can't poll any other task scheduled on that thread. Replace it with tokio::time::sleep(Duration::from_secs(1)).await. That returns Pending and lets the worker thread run other tasks until the timer fires.