Sub topic 3
Channels and async-aware Mutex
Assume Rust ownership, Send, Result, traits, and basic concurrency. This chapter uses Tokio and the futures crate.
Channels and shared state
An async channel transfers values between tasks without blocking a runtime thread. A bounded mpsc channel applies backpressure when its buffer is full. The receiver finishes when every sender is dropped.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(8);
tokio::spawn(async move {
for value in 1..=3 {
tx.send(value).await.unwrap();
}
});
while let Some(value) = rx.recv().await {
println!("{value}");
}
}For shared mutable state, use Arc<tokio::sync::Mutex<T>>. Its lock method is asynchronous. Prefer short lock durations, especially around other waits.
Keeping the runtime responsive
Blocking code prevents an executor worker from polling other futures. Move file-system calls without async APIs, CPU-heavy work, or blocking library calls to a dedicated pool:
let answer = tokio::task::spawn_blocking(|| {
(1..=1_000_000u64).sum::<u64>()
})
.await
.unwrap();Do not use spawn_blocking for ordinary async operations. Use the library's async API instead.
Cancellation by dropping futures
A future is cancelled when it is dropped. Tokio's timeout returns an error and drops its inner future after the deadline. Dropping a JoinHandle does not always stop the task; use abort when you need to request task termination. Cancellation is cooperative, so blocking or non-yielding work can delay it.
Wakers, pinning, and state machines
When a future returns Poll::Pending, it stores or registers the Waker from its Context. The waker tells the executor to poll the future again when progress may be possible.
Pin prevents a value from moving when its internal references depend on its address. Async state machines may become !Unpin; Unpin means ordinary movement is safe.
An async fn compiles into a state-machine future containing its locals and the point where it last awaited. Each poll resumes that state machine.
Streams and async traits
A Stream is an async iterator. Calling next() returns a future that produces Some(item) or None.
use futures::StreamExt;
#[tokio::main]
async fn main() {
let mut values = futures::stream::iter(1..=3).map(|x| x * 2);
while let Some(value) = values.next().await {
println!("{value}");
}
}Since Rust 1.75, traits can declare async fn directly. Each implementation supplies an async method, but such traits generally cannot be used as dyn Trait without additional design.
trait Fetcher {
async fn fetch(&self, id: u32) -> String;
}Exercise
What happens to a receiver when all senders of a Tokio mpsc channel are dropped?
Show answer
recv().await returns None, so a while let Some(...) loop ends.