Sub topic 11
Passing messages between tasks
This chapter assumes you can spawn tasks with tokio::spawn and that you know why spawned tasks must be Send + 'static. Instead of sharing memory, tasks can pass values through a channel. A channel is a queue with a sending end and a receiving end.
The mpsc channel
tokio::sync::mpsc is a multi-producer, single-consumer channel. Many tasks can send, but only one task receives. mpsc::channel(n) creates a bounded channel that holds at most n queued messages.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(8);
for i in 0..3 {
let tx = tx.clone();
tokio::spawn(async move {
tx.send(format!("worker {i}")).await.unwrap();
});
}
drop(tx);
while let Some(msg) = rx.recv().await {
println!("{msg}");
}
}Each worker gets its own clone of the Sender. Moving the clone into the task satisfies the 'static bound. The receiver must be mut because recv takes &mut self.
Closing the channel
rx.recv().await returns None once every Sender has been dropped and the queue is empty. The original tx is also a sender. Without drop(tx), the loop would wait forever. Forgetting this drop is the most common cause of a receive loop that never ends.
Backpressure
The bound matters. When the queue is full, send(...).await suspends the sender until the receiver makes room. A fast producer is slowed to the speed of a slow consumer, and memory use stays capped. This is called backpressure. mpsc::unbounded_channel() removes the limit, so a slow consumer lets the queue grow without bound. Prefer bounded channels unless you can prove the producer rate is limited.
Send errors
send returns Err when the receiver has been dropped, because nobody can read the value. The error gives the value back. In a worker, treat this as a signal to stop rather than calling unwrap. try_send never waits. It returns an error immediately if the channel is full or closed, which suits cases where you would rather drop a message than wait.
Other channel types
| Channel | Shape | Typical use |
|---|---|---|
| `mpsc` | many senders, one receiver | work queues, funneling results |
| `oneshot` | one value, one sender, one receiver | returning a reply to a request |
| `broadcast` | many senders, many receivers, each sees every message | event notifications |
| `watch` | many receivers see the latest value only | configuration or state updates |
A common pattern combines two of these. A request message carries a oneshot::Sender, and the receiving task answers through it. This gives you a simple request and response between tasks.
Exercise
Your receive loop while let Some(msg) = rx.recv().await never finishes, even though all spawned workers have completed. What is the likely cause, and how do you fix it?
Show answer
The original Sender is still alive, because only the clones were moved into the workers. recv returns None only when all senders are dropped. Call drop(tx) after spawning the workers, or move the original into the last worker.