Sub topic 9
Async I/O, sleep and timeouts
This chapter assumes you can start a Tokio runtime with #[tokio::main] and spawn tasks. It covers the three tools you need to wait on the outside world without blocking a thread: async I/O, sleep, and timeout.
Why async I/O and timers exist
A call such as std::thread::sleep or std::net::TcpStream::read blocks the whole OS thread. A Tokio worker thread that blocks cannot poll any other task. Tokio provides async versions that return a future instead. When the future is not ready, the task yields. The reactor (the part of the runtime that watches sockets and timers) wakes the task when data arrives or the timer fires.
The async versions live in a few places:
| Need | Blocking (std) | Async (Tokio) |
|---|---|---|
| Pause | `std::thread::sleep` | `tokio::time::sleep` |
| TCP | `std::net` | `tokio::net` |
| Read and write bytes | `std::io::Read`, `Write` | `tokio::io::AsyncReadExt`, `AsyncWriteExt` |
Sleeping
tokio::time::sleep returns a future that completes after a duration. Nothing happens until you .await it.
use std::time::Duration;
use tokio::time::{sleep, Instant};
#[tokio::main]
async fn main() {
let start = Instant::now();
sleep(Duration::from_millis(200)).await;
println!("waited {:?}", start.elapsed());
}Reading and writing
Tokio sockets implement AsyncRead and AsyncWrite. You use them through the extension traits AsyncReadExt and AsyncWriteExt, which you must import. A read returns Ok(0) when the peer has closed the connection.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
socket.write_all(b"hello").await.unwrap();
});
let mut client = TcpStream::connect(addr).await?;
let mut buf = Vec::new();
client.read_to_end(&mut buf).await?;
println!("{}", String::from_utf8_lossy(&buf));
Ok(())
}Binding to port 0 lets the OS pick a free port, and local_addr tells the client which one. The server task drops its socket after writing, so read_to_end sees the close and returns.
Timeouts
tokio::time::timeout wraps any future. It returns Ok(output) if the future finishes in time, or Err(Elapsed) if the deadline passes first. On timeout, the inner future is dropped.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let slow = sleep(Duration::from_secs(5));
match timeout(Duration::from_millis(100), slow).await {
Ok(()) => println!("finished"),
Err(_) => println!("timed out"),
}
}The result is nested when the wrapped future itself returns a Result. Handle the outer error (timeout) first, then the inner one (I/O).
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::net::TcpStream;
use tokio::time::timeout;
async fn read_some(stream: &mut TcpStream) -> Result<usize, String> {
let mut buf = [0u8; 64];
match timeout(Duration::from_secs(2), stream.read(&mut buf)).await {
Ok(Ok(n)) => Ok(n),
Ok(Err(e)) => Err(format!("io error: {e}")),
Err(_) => Err("read timed out".to_string()),
}
}
fn main() {}Common errors
- Forgetting
.awaitonsleeportimeout. The future is created but never polled, so no delay happens. The compiler warns that the future is unused. - Using
std::thread::sleepinside async code. It blocks the worker thread and delays every other task on it. - Forgetting to import
AsyncReadExtorAsyncWriteExt. The error says the methodreadorwrite_allis not found. - Expecting a timeout to stop side effects. Dropping the future stops it at its next
.await. Work already done, such as bytes already written, is not undone.
Exercise
A task calls timeout(Duration::from_secs(1), stream.read(&mut buf)).await and the result is Ok(Err(e)). Did the timeout expire?
Show answer
No. The outer Ok means the read finished before the deadline. The inner Err(e) is an I/O error from the read itself. A timeout would produce the outer Err(Elapsed).