Sub topic 2
Why Spawned Tasks Must Be `Send` and `'static`
Assume you know Rust ownership, borrowing, lifetimes, traits, and basic Cargo. tokio::spawn creates a task that Tokio may move between worker threads. Its future must therefore be Send, meaning it can safely move between threads. It must also be 'static, meaning it cannot borrow data that may be dropped before the task finishes. Owned data such as String usually satisfies this requirement.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let name = String::from("Ada");
let handle = tokio::spawn(async move {
sleep(Duration::from_millis(50)).await;
format!("hello, {name}")
});
match handle.await {
Ok(message) => println!("{message}"),
Err(error) if error.is_panic() => println!("task panicked"),
Err(error) => println!("task failed: {error}"),
}
}A JoinHandle is a future for the spawned task's result. Its output is Result<T, JoinError>. The Ok value is the task's return value. An error can indicate cancellation or a panic. A borrowed local variable usually fails the 'static requirement, so use move, Arc, or a channel to transfer ownership.
Async I/O, sleep, and timeouts
Tokio's timers and network types are asynchronous. When an operation cannot continue, it yields to the runtime instead of blocking an operating-system thread. timeout converts an operation that takes too long into an error.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(100), sleep(Duration::from_secs(1))).await;
println!("timed out: {}", result.is_err());
}Waiting on several futures
join! waits for all futures and returns all results. Their waits can overlap. select! waits for the first branch and drops the others, so the discarded futures must be safe to cancel.
Passing messages between tasks
Tokio channels provide ownership-safe message passing. A bounded mpsc channel applies backpressure when its buffer is full. The receiver finishes after every sender is dropped.
Exercise
Why does a spawned task commonly use async move instead of borrowing a local variable?
Show answer
async move transfers ownership into the task, helping the future satisfy the Send and 'static bounds.