Sub topic 11
Channels and async-aware Mutex
This chapter assumes you know how to spawn Tokio tasks (tokio::spawn), why spawned tasks need Send and 'static, and how Arc and move closures work. Tasks often need to talk to each other or share data. Tokio gives you two tools: channels for passing messages and Mutex for shared state.
Passing messages with mpsc
tokio::sync::mpsc is a multi-producer, single-consumer channel. Many tasks can hold a sender. One task holds the receiver.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..3 {
tx.send(i).await.unwrap();
}
});
while let Some(v) = rx.recv().await {
println!("got {v}");
}
}The number 8 is the buffer size. The channel is bounded. When 8 messages are waiting, send(...).await suspends the sender until the receiver makes room. This is backpressure. A fast producer cannot fill memory without limit.
recv().await returns Some(value) while a message arrives and None once every sender is dropped and the buffer is empty. Here the spawned task owns tx through async move. When the task finishes, tx is dropped and the loop ends.
To add more producers, call tx.clone() and move each clone into its own task.
Sharing state with Mutex
Sometimes tasks must share one value. Wrap it in Arc<Mutex<T>>. Arc lets many tasks own the value. Mutex allows one task at a time to change it.
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);
}Here lock() is a future. If another task holds the lock, this task suspends and the worker thread runs other tasks. The program prints 4.
Which Mutex should you use?
| Situation | Use |
|---|---|
| Lock is held only for a quick change, never across `.await` | `std::sync::Mutex` |
| Guard must stay alive across an `.await` | `tokio::sync::Mutex` |
The Tokio mutex is slower because it supports waiting without blocking. The standard mutex is often the better choice for short, simple updates. Its guard is not Send, so holding it across .await in a spawned task fails to compile. That error is the compiler protecting you.
Common errors
- Receiver never ends. A
while let Some(..)loop hangs if a sender is still alive, such as the originaltxleft inmain. Drop it or move it into a task. sendreturnsErr. The receiver was dropped. Decide whether to stop or ignore it.- Deadlock. Two tasks each hold one lock and wait for the other. Lock in a consistent order.
Exercise
In the mpsc example, why does the while let loop finish, and what would happen if main kept its own copy of tx alive?
Show answer
The loop finishes because recv() returns None once all senders are dropped and the buffer is empty. The spawned task owns the only sender, and it drops it when the task ends. If main kept another tx, a sender would still exist, so recv() would keep waiting and the loop would never end.
Exercise
When should you choose tokio::sync::Mutex over std::sync::Mutex?
Show answer
Choose the Tokio mutex when the guard must be held across an .await. For short updates with no .await while locked, the standard mutex is simpler and faster.