Sub topic 2
Async timers and I/O
Assume ownership, borrowing, Result, traits, and Cargo dependencies. This chapter uses Tokio with the full feature:
tokio = { version = "1", features = ["full"] }Async timers and I/O
Tokio provides asynchronous versions of waiting and I/O. sleep pauses a future without blocking an operating-system thread. tokio::fs::read performs file I/O through Tokio’s runtime.
Spawning tasks and joining their handles
tokio::spawn starts a future as an independent task. Its JoinHandle is itself a future. Awaiting the handle gives a Result: the inner value, or a JoinError if the task panicked or was cancelled.
use std::{error::Error, time::Duration};
use tokio::{
fs,
time::{sleep, timeout},
};
async fn read_len(path: &str) -> std::io::Result<usize> {
Ok(fs::read(path).await?.len())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let timer = tokio::spawn(async {
sleep(Duration::from_millis(100)).await;
"timer finished"
});
let file = tokio::spawn(async { read_len("Cargo.toml").await });
let (timer_result, file_result) = tokio::join!(timer, file);
println!("{}", timer_result?);
println!("file length: {}", file_result??);
match timeout(Duration::from_millis(50), sleep(Duration::from_secs(1))).await {
Ok(_) => println!("completed"),
Err(_) => println!("timed out"),
}
Ok(())
}`Send` and `'static` requirements
A spawned task may run on a different worker thread and may outlive the function that created it. Therefore, its future must be Send and 'static.
Send means a value can move safely between threads. 'static means the future does not borrow data that might disappear. Use async move to move owned values into a task. An Arc can share owned data safely.
Concurrent composition
join! waits for all futures and returns every result. select! waits for the first branch and drops the losing future.
Propagating errors
The ? operator works inside async fn exactly as it does in synchronous code. It returns early when an awaited operation produces an error.
Exercise
Why can read_len use ? after fs::read(path).await?
Show answer
Awaiting produces a Result; ? returns its error from read_len or unwraps its successful byte vector.