Async I/O and timers
Quick answer
Asynchronous I/O lets tasks wait for readiness without blocking their executor thread. Timers similarly suspend the task until time conditions are met.
Read the required bytes and await time
Tokio's AsyncReadExt and AsyncWriteExt provide convenient methods for asynchronous streams. A read may return fewer bytes than requested; read_exact is appropriate when a protocol requires a known length. write_all sends the entire buffer or returns an error, but cancellation may leave a partial write. tokio::time::sleep yields while waiting. The in-memory duplex stream avoids external network dependencies.
use tokio::io::{AsyncReadExt, AsyncWriteExt};#[tokio::main(flavor = "current_thread")]async fn main() { let (mut a, mut b) = tokio::io::duplex(8); a.write_all(b"hi").await.unwrap(); let mut buf = [0; 2]; b.read_exact(&mut buf).await.unwrap(); println!("{}", std::str::from_utf8(&buf).unwrap());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
hiThe buffer capacity exceeds the message length, so writing before reading works here.
#[tokio::main(flavor = "current_thread")]async fn main() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; println!("timer complete");}Manual local Rust/Cargo candidate; not executed. Expected behavior:
timer complete; actual elapsed time varies.The task can suspend instead of blocking the runtime thread.
Common mistake
Do not assume a single read produces a complete message, or that a timer fires at an exact wall-clock instant.
Try it yourself
Increase the message to four bytes and update the receiving buffer; keep the capacity large enough.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async I/O and timers — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A stream delivers a protocol header in fragments. Which extension method helps read the required full header?
Async I/O and timers — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main(flavor = "current_thread")] async fn main() { let (mut a, mut b) = tokio::io::duplex(8); a.write_all(b"hi").await.unwrap(); let mut buf = [0; 2]; b.read_exact(&mut buf).await.unwrap(); println!("{}", std::str::from_utf8(&buf).unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Async I/O and timers — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[tokio::main(flavor = "current_thread")] async fn main() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; println!("timer complete"); } ``` Which outcome or interpretation best matches this example?