Sub topic 12
Channels and async-aware Mutex
This chapter assumes you can spawn tasks with tokio::spawn, that you know why spawned tasks need Send and 'static, and that you are comfortable with Arc and move closures. Tasks often need to cooperate. Because a spawned future must be 'static, it cannot borrow local variables from its parent. Tasks therefore either send messages to each other or share state behind a lock. Tokio supports both.
Message passing with `mpsc`
tokio::sync::mpsc is a multi-producer, single-consumer channel. You get a Sender and a Receiver from mpsc::channel(capacity). The capacity is the number of messages the channel buffers before senders have to wait.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(4);
for id in 0..3 {
let tx = tx.clone();
tokio::spawn(async move {
tx.send(format!("worker {id} done")).await.unwrap();
});
}
drop(tx);
while let Some(msg) = rx.recv().await {
println!("{msg}");
}
}Each worker gets its own clone of the sender. The loop ends when recv() returns None, which happens only after every sender has been dropped. The original tx is still alive in main, so drop(tx) is required. Without it the loop waits forever.
Backpressure and closing
send is async. When the buffer is full, send(...).await suspends the sender until the receiver makes room. This is backpressure, and it keeps a fast producer from filling memory. mpsc::unbounded_channel() has no limit and a synchronous send. Use it only when you can bound the producer some other way.
Closing is reported through return values:
recv()returnsNonewhen all senders are dropped and the buffer is empty.send()returnsErrwhen the receiver is dropped. The error hands the unsent value back to you.
Treat a failed send as a shutdown signal. Calling unwrap() on it, as the examples do for brevity, panics the task instead.
Other channel types
| Channel | Shape | Typical use |
|---|---|---|
| `mpsc` | many senders, one receiver | work queues, event streams |
| `oneshot` | one value, one sender, one receiver | reply to a single request |
| `broadcast` | many senders, many receivers, each receiver sees every message | fan-out notifications |
| `watch` | many receivers see only the latest value | configuration, shutdown flags |
Request and reply with `oneshot`
A common pattern is a task that owns some state and serves commands over a channel, often called an actor. Each command that needs an answer carries a oneshot::Sender for the reply.
use tokio::sync::{mpsc, oneshot};
enum Command {
Add(u32),
Get(oneshot::Sender<u32>),
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<Command>(16);
let actor = tokio::spawn(async move {
let mut total = 0;
while let Some(cmd) = rx.recv().await {
match cmd {
Command::Add(n) => total += n,
Command::Get(reply) => {
let _ = reply.send(total);
}
}
}
});
tx.send(Command::Add(2)).await.unwrap();
tx.send(Command::Add(3)).await.unwrap();
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Command::Get(reply_tx)).await.unwrap();
println!("total = {}", reply_rx.await.unwrap());
drop(tx);
actor.await.unwrap();
}Only the actor touches total, so no lock is needed. Awaiting reply_rx returns Err if the actor drops the reply sender without sending, so a crashed actor cannot leave the caller waiting forever.
Shared state with `Arc<Mutex<T>>`
When several tasks need direct access to the same value, wrap it in Arc so every task owns a handle, and in a Mutex so only one task mutates it at a time.
use std::sync::Arc;
use tokio::sync::Mutex;
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(tokio::spawn(async move {
let mut guard = counter.lock().await;
*guard += 1;
}));
}
for h in handles {
h.await.unwrap();
}
println!("{}", *counter.lock().await);
}tokio::sync::Mutex::lock() is async. A task that finds the lock taken is suspended, and its worker thread runs other tasks. The lock is also fair: waiters acquire it in the order they asked.
Which Mutex to use
The standard library std::sync::Mutex blocks the whole thread while waiting. That sounds wrong in async code, but it is the better choice when you hold the lock briefly and never across an .await:
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let hits = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let hits = Arc::clone(&hits);
handles.push(tokio::spawn(async move {
{
let mut guard = hits.lock().unwrap();
*guard += 1;
}
tokio::task::yield_now().await;
}));
}
for h in handles {
h.await.unwrap();
}
println!("{}", *hits.lock().unwrap());
}The guard lives in an inner block and is dropped before the .await. This matters because a std guard is not Send. If it were alive across an .await, the future would not be Send and tokio::spawn would reject it at compile time.
Common errors
- Receive loop never ends. A sender is still alive, usually the original
txkept in the parent task. Drop it, or move it into the last task. - Deadlock with an async Mutex. Holding a guard while awaiting something that needs the same lock hangs both tasks. Keep critical sections small, and copy data out of the guard before awaiting.
- Inconsistent lock order. Two tasks that take locks A and B in opposite orders can wait on each other forever. Always acquire locks in the same order.
- Future is not
Send. Astdguard, or anRc, is held across an.await. Scope it in a block, or switch to the Tokio mutex. - Unbounded growth. An unbounded channel with a slow consumer grows without limit. Prefer a bounded channel.
- Ignoring
senderrors. AnErrmeans the receiver is gone. Stop producing instead of unwrapping.
Choosing between channels and locks
Prefer channels when one task can own the data and others only request changes. This avoids lock ordering problems and makes the flow of work visible. Prefer a mutex when many tasks need quick access to a small shared value and an owner task would add needless indirection. Neither choice is required. Real programs often combine them.
Exercise
A worker pool spawns three tasks that each hold a clone of tx from mpsc::channel. The main task loops with while let Some(m) = rx.recv().await. All workers finish, but the program hangs at the loop. What is the most likely cause, and how do you fix it?
Show answer
The original tx is still alive in the main task, so the channel is not closed and recv() keeps waiting. Call drop(tx) after cloning it for the workers, or move the original into the last worker, so the loop sees None once all workers finish.