Sub topic 11
Passing messages between tasks
This chapter assumes you can spawn tasks with tokio::spawn, you know why those tasks must be Send + 'static, and you are comfortable with Arc and ownership moves into async move blocks. Here you will learn to connect tasks with Tokio's channels, so they can communicate without sharing locked data.
Why channels
Tasks often need to hand work or results to each other. You can share state behind a mutex, or you can give one task ownership of the state and let others send it messages. Channels support the second style. Each value has one owner at a time, ownership moves through the channel, and no lock is needed.
Tokio ships four channel types in tokio::sync. Each fits a different shape of communication.
| Channel | Producers | Consumers | Values kept | Typical use |
|---|---|---|---|---|
| `mpsc` | many | one | queue of messages | work queues, actors |
| `oneshot` | one | one | exactly one value | a reply to a request |
| `broadcast` | many | many | every receiver sees every message | events, shutdown signals |
| `watch` | one writer (or several via `send_modify`) | many | only the latest value | configuration, status |
mpsc: many senders, one receiver
mpsc::channel(capacity) returns a Sender<T> and a Receiver<T>. The sender is Clone, so each producing task gets its own copy. The receiver is not Clone, which is what guarantees a single consumer.
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}");
}
}The drop(tx) line is easy to forget. recv() returns None only when every sender has been dropped. The original tx is still alive in main, so without the drop the loop would wait forever even after all workers finish.
Bounded channels and backpressure
The capacity you pass to channel is a limit on queued messages. When the queue is full, send(...).await suspends the sending task until the receiver makes room. That suspension is backpressure. A fast producer cannot outrun a slow consumer and fill memory.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(2);
let producer = tokio::spawn(async move {
for i in 0..5 {
tx.send(i).await.unwrap();
println!("sent {i}");
}
});
while let Some(v) = rx.recv().await {
sleep(Duration::from_millis(50)).await;
println!("received {v}");
}
producer.await.unwrap();
}Run this and you will see the first sends return immediately, then the producer stalls until the consumer takes a message. The exact interleaving of output lines can vary, but the producer never gets more than a few messages ahead.
Tokio also offers mpsc::unbounded_channel(). Its send is not async and never waits. Use it only when the producer is naturally limited, or when you must send from non-async code. Otherwise a stalled consumer lets the queue grow without limit.
If you cannot wait, use try_send. It returns Err(TrySendError::Full(_)) immediately when the queue is full, which lets you drop or count the message instead.
Errors you will meet
sendreturnsErr(SendError(value))when the receiver has been dropped or closed. The error hands your value back. In a worker, this usually means "the consumer is gone, stop working".recvreturnsNoneonce all senders are dropped and the queue is empty. Messages already queued are still delivered first.- Calling
rx.close()stops new sends but lets you drain what is already queued.
Unwrapping send is fine in small examples. In real services, decide what a closed channel means for that task, and usually exit the task cleanly.
oneshot: replying to a request
A oneshot channel carries exactly one value. Sender::send consumes the sender and is not async, because a single slot is always available. Receiver is a future you .await.
Combining mpsc with oneshot gives a request/response pattern. A task owns some state, and other tasks send it commands that include a oneshot::Sender to carry the answer back. This is often called the actor pattern.
use tokio::sync::{mpsc, oneshot};
enum Command {
Add { amount: u32, reply: 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 = 0u32;
while let Some(cmd) = rx.recv().await {
match cmd {
Command::Add { amount, reply } => {
total += amount;
let _ = reply.send(total);
}
}
}
});
for n in [5, 10] {
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Command::Add { amount: n, reply: reply_tx })
.await
.unwrap();
println!("total = {}", reply_rx.await.unwrap());
}
drop(tx);
actor.await.unwrap();
}The total variable lives in one task and is never shared, so it needs no mutex. The actor also ends on its own: when the last tx is dropped, recv returns None and the loop exits.
Two details matter. The actor ignores the result of reply.send with let _ =, because the requester may have given up and dropped its receiver. And reply_rx.await returns Err(RecvError) if the actor drops the sender without replying, for example after a panic. Handle that case rather than unwrapping in production code.
broadcast: every receiver gets every message
broadcast::channel(capacity) delivers each message to all receivers. Create new receivers by calling tx.subscribe(). A receiver only sees messages sent after it subscribed.
use tokio::sync::broadcast;
#[tokio::main]
async fn main() {
let (tx, mut rx1) = broadcast::channel::<String>(16);
let mut rx2 = tx.subscribe();
tx.send("hello".to_string()).unwrap();
println!("{}", rx1.recv().await.unwrap());
println!("{}", rx2.recv().await.unwrap());
}The channel stores up to capacity messages in a ring buffer. A receiver that falls too far behind loses the oldest messages, and its next recv returns Err(RecvError::Lagged(n)), where n is how many it missed. The following recv continues with the oldest message still available. Messages are cloned for each receiver, so T must be Clone.
watch: the latest value
watch::channel(initial) holds one value that many receivers can observe. Writers overwrite it, and receivers see only the newest value, never a backlog. A receiver calls changed().await to wait for an update and borrow() to read the current value. This fits settings that change rarely, or a "shutting down" flag, where intermediate values do not matter.
Choosing a channel
- Many tasks produce work for one consumer:
mpsc, bounded unless you have a reason. - You need one answer back:
oneshot, usually inside anmpscmessage. - Everyone must see every event:
broadcast. - Everyone needs the current state only:
watch.
Common mistakes
- Holding a spare
Senderand wondering why the receiver never finishes. - Choosing a huge capacity to "avoid blocking". This hides backpressure instead of handling it. Pick a capacity that reflects how much work you are willing to buffer.
- Using
std::sync::mpscbetween tasks. Itsrecvblocks the worker thread, which stalls other tasks on that thread. Use Tokio's channel inside async code. - Sending a very large value by moving it through a channel repeatedly. Send an
Arc<T>or an ID instead.
Exercise
A program creates let (tx, mut rx) = mpsc::channel::<u32>(4);, spawns three tasks that each own a clone of tx and send one number, then runs while let Some(n) = rx.recv().await { println!("{n}"); } in main. It prints three numbers and then hangs. What is wrong, and how do you fix it?
Show answer
The original tx is still alive in main, so the channel never closes and recv keeps waiting. Add drop(tx); after the clones are created and before the receive loop (or move the original into the last task instead of cloning it).
Exercise
A producer sends on mpsc::channel(2) and the consumer sleeps 50 ms per message. What happens to the producer after it has queued two messages, and which method would let it skip the message instead of waiting?
Show answer
send(...).await suspends the producer until the consumer removes a message and frees a slot. That is backpressure. try_send returns Err(TrySendError::Full(_)) immediately, so the producer can drop or count the message instead of waiting.
Exercise
You need ten worker tasks to all learn that the application is shutting down, and a worker that starts late should still see the flag. Which channel fits best and why?
Show answer
watch. It stores the latest value, so a receiver created after the flag was set still reads the current state with borrow(). A broadcast receiver only sees messages sent after it subscribed, so a late worker would miss the signal.