Sub topic 9
Async I/O, sleep and timeouts
This chapter assumes you know Rust ownership and closures, can use Cargo with external crates, and have read the earlier chapters on futures, #[tokio::main] and tokio::spawn. Here you will see how Tokio performs I/O and waits without blocking a thread, and how to put a time limit on any operation.
Why async I/O needs its own types
A call to std::net::TcpStream::read blocks the calling thread until data arrives. On a Tokio worker thread, that stops every other task scheduled on that thread. Tokio therefore ships its own versions of the I/O types. Their operations return futures. When no data is ready, the future returns Poll::Pending, the task yields, and the worker thread runs something else.
The reactor, which the runtime chapter described, watches the operating system for readiness events (epoll on Linux, kqueue on macOS, IOCP on Windows). When a socket becomes readable, the reactor wakes the task that waited on it.
The I/O traits
Tokio defines AsyncRead and AsyncWrite, but you rarely call their methods directly. You use the extension traits AsyncReadExt and AsyncWriteExt from tokio::io. They add methods that return futures.
| Method | Trait | Behavior |
|---|---|---|
| `read(&mut buf)` | `AsyncReadExt` | Reads some bytes into `buf`. Returns the count. `Ok(0)` means end of stream (when `buf` is not empty). |
| `read_exact(&mut buf)` | `AsyncReadExt` | Fills the whole buffer or fails with `UnexpectedEof`. |
| `read_to_end(&mut vec)` | `AsyncReadExt` | Reads until the peer closes. |
| `write(&buf)` | `AsyncWriteExt` | Writes some bytes. It may write fewer than `buf.len()`. |
| `write_all(&buf)` | `AsyncWriteExt` | Loops until every byte is written. |
| `flush()` | `AsyncWriteExt` | Pushes buffered data to the underlying writer. |
Two details cause most beginner bugs here:
readreturns however many bytes are available, not however many you hoped for. A message sent in onewriteon the peer can arrive in several reads, and several messages can arrive in one read. TCP is a byte stream with no message boundaries.writemay be partial. Preferwrite_allunless you handle the returned count yourself.
You must import the extension traits. If you see "no method named read found", the missing use tokio::io::AsyncReadExt; is almost always the cause.
A TCP client
The next program connects to a server, sends a request and reads the reply. It needs the net and io-util features, which the full feature enables.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("example.com:80").await?;
stream
.write_all(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
.await?;
let mut response = Vec::new();
stream.read_to_end(&mut response).await?;
println!("received {} bytes", response.len());
Ok(())
}TcpStream::connect resolves the name and connects without blocking a worker thread. HTTP/1.0 is used so the server closes the connection after replying, which lets read_to_end finish.
Files are different
Operating systems do not offer readiness notifications for regular files in the way they do for sockets. tokio::fs therefore runs each file operation on the blocking thread pool, the same pool that spawn_blocking uses.
use tokio::fs;
#[tokio::main]
async fn main() -> std::io::Result<()> {
fs::write("hello.txt", b"hello from tokio").await?;
let text = fs::read_to_string("hello.txt").await?;
println!("{text}");
fs::remove_file("hello.txt).await?;
Ok(())
}Wait: that last call has a typo, and the string literal is not closed. The corrected line is:
fs::remove_file("hello.txt").await?;The async API is convenient, but each call costs a hop to another thread. For many small reads, read once into memory or use a buffered reader instead of issuing many tiny calls.
Buffered I/O
Calling read for one byte at a time is a system call per byte. Wrap the stream in BufReader when you read line by line, and in BufWriter when you make many small writes.
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::TcpStream;
async fn first_line(stream: TcpStream) -> std::io::Result<String> {
let mut reader = BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).await?;
Ok(line)
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let stream = TcpStream::connect("example.com:80").await?;
let line = first_line(stream).await?;
println!("{line:?}");
Ok(())
}With BufWriter, remember to call flush().await before you drop it. Dropping cannot run async code, so buffered bytes can be lost.
Sleeping without blocking
tokio::time::sleep(duration) returns a future that completes after the duration has passed. While it waits, the thread is free. Compare it with std::thread::sleep, which holds the worker thread idle.
use std::time::{Duration, Instant};
use tokio::time::sleep;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
let a = tokio::spawn(async {
sleep(Duration::from_millis(200)).await;
});
let b = tokio::spawn(async {
sleep(Duration::from_millis(200)).await;
});
a.await.unwrap();
b.await.unwrap();
println!("elapsed about {} ms", start.elapsed().as_millis());
}Even on a single thread, this prints about 200 ms, not 400, because both tasks wait on timers at the same time. Replace sleep with std::thread::sleep and the output becomes about 400 ms, since the single thread cannot run the second task while the first one sleeps.
A sleep future is lazy. It starts counting from when it is created, not from when it is first polled, so creating one early and awaiting it later shortens the wait. For a reusable deadline, use sleep_until(Instant) with tokio::time::Instant.
Intervals
tokio::time::interval(period) produces a repeating timer. Call tick().await to wait for the next tick.
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}");
}
}The first tick completes immediately. After that, ticks arrive every period. If your loop body takes longer than the period, the interval has missed ticks. By default it fires them in a burst to catch up. You can change this with set_missed_tick_behavior, for example to MissedTickBehavior::Delay, which spaces ticks a full period after the late one.
Timeouts
tokio::time::timeout(duration, future) wraps any future. It returns Ok(output) if the future finishes in time, and Err(Elapsed) if not. When the deadline passes, the inner future is dropped.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn slow_job() -> &'static str {
sleep(Duration::from_secs(2)).await;
"done"
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(300), slow_job()).await {
Ok(result) => println!("finished: {result}"),
Err(_) => println!("gave up after 300 ms"),
}
}When the wrapped future itself returns a Result, you get a nested Result. Handle both layers:
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::net::TcpStream;
use tokio::time::timeout;
async fn read_with_deadline(stream: &mut TcpStream) -> std::io::Result<usize> {
let mut buf = [0u8; 512];
match timeout(Duration::from_secs(5), stream.read(&mut buf)).await {
Ok(Ok(n)) => Ok(n),
Ok(Err(e)) => Err(e),
Err(_) => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"read timed out",
)),
}
}
#[tokio::main]
async fn main() {
let mut stream = TcpStream::connect("example.com:80").await.unwrap();
match read_with_deadline(&mut stream).await {
Ok(n) => println!("read {n} bytes"),
Err(e) => println!("error: {e}"),
}
}Here the server waits for a request and sends nothing, so the read times out after five seconds.
What a timeout cannot do
A timeout only works at .await points. The runtime can drop a future only when the future returns Pending to it. A future that runs a long loop without awaiting never yields, so the timeout cannot fire until the loop ends. For CPU-heavy work, use spawn_blocking, covered in a later chapter.
Dropping the inner future also cancels it midway. If it was halfway through a multi-step write, the peer sees partial data. Chapter on cancellation covers which operations are safe to cancel. As a rule, read, accept, and sleep are safe to abandon. write_all is not, because some bytes may already have been sent.
Choosing between the tools
| Need | Tool |
|---|---|
| Pause this task for a fixed time | `sleep` |
| Run something repeatedly on a schedule | `interval` |
| Limit how long one operation may take | `timeout` |
| Stop at an absolute point in time | `timeout_at` or `sleep_until` |
| Race an operation against several events | `select!` (next chapter) |
Exercise
A task runs timeout(Duration::from_secs(1), stream.write_all(&big_buffer)).await and the timeout fires. Is it safe to keep using stream afterward for another write? Explain why or why not.
Show answer
No. write_all loops over partial writes. When the timeout drops the future, an unknown number of bytes may already have been sent, so the peer has received a partial message. Writing again would corrupt the stream framing. After such a timeout, close the connection (or track how many bytes were written and resume from there with write).
Exercise
Two tasks each call std::thread::sleep(Duration::from_millis(200)) on a current_thread runtime. How long does the program take, and what changes if you switch to tokio::time::sleep?
Show answer
About 400 ms with std::thread::sleep, because the single thread is blocked during each sleep and the tasks run one after the other. With tokio::time::sleep the tasks wait on timers concurrently, so the total is about 200 ms.
Exercise
timeout(d, fut).await returns Result<Result<usize, io::Error>, Elapsed> when fut reads from a socket. Write a match that maps all three outcomes to a single io::Result<usize>.
Show answer
match timeout(d, fut).await { Ok(Ok(n)) => Ok(n), Ok(Err(e)) => Err(e), Err(_) => Err(io::Error::new(io::ErrorKind::TimedOut, "timed out")) }