Rust
Multiple producers
Build a multi-producer channel with tx.clone().
Multiple producers
The "multiple producer" part of mpsc: you can duplicate the sender with clone and give each producer a copy. All messages gather at a single receiver (fan-in):
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
for j in 0..2 {
tx.send(format!("üretici {id}: {j}")).unwrap();
}
});
}
drop(tx); // if the main copy isn't dropped, rx never closes
Messages from different producers can interleave; only messages from the same producer are ordered among themselves.
Deterministic output
The arrival order of messages changes from run to run. For testable output, messages are collected and sorted, or only order-independent summaries are printed:
let mut hepsi: Vec<String> = rx.iter().collect();
hepsi.sort();
println!("{} {}", hepsi.len(), hepsi[0]);
Exercise Three producers
Start three producer threads; let each send two messages as üretici ID: J (J = 0, 1). Drop the main sender, collect all messages, sort them; print the message count and the first message separated by a space.
Show example solution
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
for j in 0..2 {
tx.send(format!("üretici {id}: {j}")).unwrap();
}
});
}
drop(tx);
let mut hepsi: Vec<String> = rx.iter().collect();
hepsi.sort();
println!("{} {}", hepsi.len(), hepsi[0]);
}
Test yourself
-
Can the receiver be cloned (<code>rx.clone()</code>)?
- Only in tokio
- No; mpsc has a single consumer
- Yes
- Only with Arc
Show answer
No; mpsc has a single consumer — If many consumers are needed, the receiver is put in an Arc<Mutex<Receiver>>, or crossbeam/tokio broadcast channels are used.
-
Duplicate the sender
for id in 0..3 {
let tx = tx.____();
thread::spawn(move || tx.send(id).unwrap());
}
Show answer
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || tx.send(id).unwrap());
}
-
Concept and meaning
- tx.clone()
- New producer
- fan-in
- Many to one gathering
- drop(tx)
- Close the main copy
- rx.clone()
- Not possible
Next lesson: try_recv