Sub topic 6
Many producers, one consumer
This chapter assumes you can spawn and join threads, write move closures, and send values through a basic mpsc channel. It shows how several threads send into one channel and how to make the receiving loop end.
What mpsc means
mpsc stands for "multiple producer, single consumer". A channel has two ends, and they differ in what you can do with them:
Sender<T>implementsClone. Each clone sends into the same channel.Receiver<T>does not implementClone. Only one thread owns the receiving end at a time.
So you can have many threads writing and one thread reading. Cloning a Sender is cheap, and it is the way to add producers.
Cloning the sender
Each producer thread needs its own Sender, because a move closure takes ownership of what it captures. Clone inside the loop, before the spawn.
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();
}
}The line let tx = tx.clone(); shadows the outer tx with a clone that lives only in that loop iteration. The move closure then takes the clone. The original tx stays in main.
Why the original sender must be dropped
The for msg in rx loop ends when the channel is closed. A channel closes for receiving once every Sender has been dropped. Each worker's clone is dropped when its thread finishes. The original tx is still alive in main, so without drop(tx) the loop waits forever for a message that can never come.
Ordering
Messages from one sender arrive in the order that sender sent them. Messages from different senders interleave in whatever order the threads happen to run. Running the example twice can print the three lines in different orders. Do not write code that depends on a particular interleaving. If you need to know which producer sent a message, put the id in the message, as the example does.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Moving `tx` into the closure without cloning | Compile error: use of moved value in the second iteration | Call `tx.clone()` before `spawn` |
| Forgetting `drop(tx)` | The receive loop never ends | Drop the original sender after creating the clones |
| Trying to clone the `Receiver` | Compile error: no method `clone` | Keep one consumer, or share the receiver behind `Arc<Mutex<_>>` (a later chapter) |
| Joining producers before reading with an unbounded channel | Works, but all messages are buffered in memory first | Read from the receiver first, or use a bounded channel |
The last row is not an error. It is a reminder that channel() has no size limit, so a fast producer can fill memory if the consumer is slow. A later chapter covers bounded channels.
Why this is safe
Sender<T> can be moved to another thread when T is Send. The compiler checks this when you call spawn. A String is Send, so the example compiles. If you tried to send an Rc<String>, the compiler would reject it, because Rc is not Send.
Exercise
In the example above, you remove the line drop(tx); and run the program. All three "worker done" lines print, but the program never exits. Why, and what is the smallest change that fixes it?
Show answer
The for msg in rx loop only ends when every Sender is dropped. The three clones are dropped as their threads finish, but the original tx still lives in main and keeps the channel open, so the loop waits forever. Restoring drop(tx); before the receive loop fixes it.
Exercise
Three threads each send the numbers 0, 1, 2 into one channel. Is it guaranteed that the receiver sees 0, 1, 2, 0, 1, 2, 0, 1, 2? What is guaranteed?
Show answer
No. Messages from different senders interleave in an unspecified order. Only the order within each single sender is guaranteed, so each thread's 0 arrives before its own 1, and its 1 before its own 2.