Sub topic 6
Many producers, one consumer
This chapter covers the "mpsc" in std::sync::mpsc: multiple producer, single consumer. You will clone a Sender, hand each clone to a thread, and collect messages in one place. It assumes you know how to spawn and join threads, why thread closures use move, and the basics of a channel with one Sender and one Receiver.
Why a channel has many senders but one receiver
A channel from mpsc::channel() has two ends. Sender<T> is the sending end and Receiver<T> is the receiving end. The name says what the types allow:
Sender<T>implementsClone. You can have as many senders as you like.Receiver<T>does not implementClone. There is exactly one receiver, and it can be moved to another thread but not copied.
Every clone of a Sender feeds the same queue. Messages from different senders interleave in the order they arrive. Messages from a single sender keep that sender's order.
Cloning a Sender for each thread
A move closure takes ownership of what it captures. If you move tx into the first thread, you can no longer use it for the second. The fix is to clone the sender once per thread and move the clone.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let mut handles = Vec::new();
for id in 0..3 {
let tx = tx.clone();
handles.push(thread::spawn(move || {
tx.send(format!("worker {id} done")).unwrap();
}));
}
drop(tx);
for msg in rx {
println!("{msg}");
}
for h in handles {
h.join().unwrap();
}
}Three details in this program matter.
let tx = tx.clone();shadows the outertxinside the loop body. The closure captures the clone. The original is untouched.- The
idvalue is also moved into the closure. For an integer this is a copy, so each thread gets its own number. drop(tx)discards the original sender. This line is easy to forget, and the next section explains why it is required.
Cloning a Sender is cheap. It does not copy the queue or the messages. It creates another handle to the same channel and increments an internal count of live senders.
Why you must drop the original sender
A loop such as for msg in rx ends when recv returns an error. That happens only when the queue is empty and every sender is gone. After the loop above spawns three workers, there are four senders in total: the three clones inside the threads and the original tx in main.
Each clone is dropped when its thread finishes. The original stays alive until main ends. If you remove drop(tx), the receiving loop prints the three messages and then blocks forever. The program hangs, and no error is reported, because from the channel's point of view a sender that could still send exists. That sender is in the same thread that is waiting.
There are two ways to avoid the leftover sender.
- Call
drop(tx)after the last clone is made, as above. - Do not keep the original at all. Create the channel, then clone for each worker and move the original into the last one.
The first approach is easier to read and harder to get wrong when the number of workers changes.
What order do messages arrive in?
The order across senders is not fixed. It depends on how the operating system schedules the threads. Run the program above several times and you may see worker 2 done first on one run and worker 0 done first on another.
What is guaranteed is per-sender order. If one thread sends 1, 2, 3, the receiver sees them in that order. Messages from other threads may appear between them.
| Property | Guaranteed? |
|---|---|
| Every sent message is delivered, if the receiver keeps reading | Yes |
| One sender's messages arrive in the order it sent them | Yes |
| Messages from different senders arrive in a fixed order | No |
| Output of the program is identical on every run | No |
If your logic needs a deterministic result, do not depend on arrival order. Either sort after collecting, or put an identifier in each message so the receiver can place it correctly.
Sending richer messages
A message can be any type that is Send. For several producers it is usually better to send a struct or an enum than a bare string, so the receiver knows who sent it and what happened.
use std::sync::mpsc;
use std::thread;
enum Event {
Progress { worker: usize, percent: u8 },
Finished { worker: usize, total: u32 },
}
fn main() {
let (tx, rx) = mpsc::channel::<Event>();
let mut handles = Vec::new();
for worker in 0..3 {
let tx = tx.clone();
handles.push(thread::spawn(move || {
let mut total = 0u32;
for step in 1..=4u32 {
total += step * (worker as u32 + 1);
tx.send(Event::Progress {
worker,
percent: (step * 25) as u8,
})
.unwrap();
}
tx.send(Event::Finished { worker, total }).unwrap();
}));
}
drop(tx);
let mut totals = vec![0u32; 3];
for event in rx {
match event {
Event::Progress { worker, percent } => {
println!("worker {worker}: {percent}%");
}
Event::Finished { worker, total } => {
totals[worker] = total;
}
}
}
for h in handles {
h.join().unwrap();
}
println!("totals = {totals:?}");
}The progress lines can appear in any interleaving, but totals is always [10, 20, 30]. Each result carries its worker index, so the final answer does not depend on arrival order. This is the pattern to copy when you need correct output from unordered messages.
One consumer is a real limit
Because Receiver cannot be cloned, only one thread can read from a channel. That is what "single consumer" means. Two things follow.
- The consumer is a single point of serialization. If handling a message is slow, producers pile up messages in the queue, and the queue is unbounded for
channel(). - You cannot fan work out to several readers by cloning the receiver. A later chapter shows the worker pool pattern, which wraps the receiver in
Arc<Mutex<_>>to share it. Bounded channels are covered after that, and they limit how far producers can run ahead.
For now, the rule is simple. Many threads may send, and one thread receives.
Errors when producers and the consumer disagree
Sending can fail too. send returns Err if the Receiver has been dropped, because nobody can ever read the message. The error returns the value inside SendError, so you can recover it.
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
drop(rx);
match tx.send(String::from("hello")) {
Ok(()) => println!("sent"),
Err(e) => println!("receiver gone, got back: {}", e.0),
}
}With several producers, this matters in a practical way. If the consumer exits early, perhaps after finding the first answer it needed, each producer's next send returns Err. Using unwrap() on that result would make every producer panic. A producer that can outlive its consumer should treat a failed send as a signal to stop:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u32>();
let mut handles = Vec::new();
for id in 0..3u32 {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for n in 0.. {
if tx.send(id * 1000 + n).is_err() {
break;
}
}
}));
}
drop(tx);
let first_five: Vec<u32> = rx.iter().take(5).collect();
drop(rx);
for h in handles {
h.join().unwrap();
}
println!("collected {} messages", first_five.len());
}The consumer takes five messages and drops the receiver. Each producer's next send fails, the loop breaks, and the joins return. Without the is_err check, the producers would panic, and join().unwrap() would then panic in main.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Moving `tx` into the first thread inside a loop | Compile error: value moved in previous iteration | Clone with `tx.clone()` inside the loop |
| Forgetting `drop(tx)` | Receiving loop hangs after the last message | Drop the original sender after cloning |
| Calling `unwrap()` on `send` in a producer that may outlive the consumer | Producer panics when the receiver is dropped | Check `is_err()` and stop |
| Relying on arrival order across threads | Output differs between runs | Tag messages with an id and sort or index |
| Joining producers before reading when the channel is bounded | Deadlock | Read from the receiver first, then join |
Exercise
A program creates a channel, spawns four threads that each receive a clone of the sender and send one number, and then runs for n in rx { println!("{n}"); } in main. All four numbers print, but the program never exits. The original tx is still in scope in main. What is wrong, and what is the smallest change that fixes it?
Show answer
The original tx in main is still alive, so the channel never reports that all senders are gone. The for loop keeps waiting for a message that the main thread itself could still send. Add drop(tx); after the last clone is made and before the receiving loop. When the four worker threads finish, their clones are dropped, no senders remain, and the loop ends.
Exercise
Four producers each send ten messages, labeled with their own id, over one channel. Which of these can you rely on in the receiver: (a) all forty messages arrive, (b) producer 2's messages arrive in the order it sent them, (c) all of producer 1's messages arrive before any of producer 3's?
Show answer
(a) and (b). Every message is delivered as long as the receiver keeps reading, and one sender's messages keep their order. (c) is not guaranteed because thread scheduling decides how messages from different senders interleave.