Systems Advanced
19 Channels
Instead of sharing memory, pass messages. An mpsc channel has many senders and one receiver. When every sender is dropped, iterating the receiver ends -- that is how the loop knows to stop.
In fan_in, spawn workers threads where worker i sends i * 10. Collect everything received into a sorted vec.
Hints
- Clone the sender for each worker:
let tx = tx.clone();. - Drop the original
txbefore collecting, or the receiver waits forever for a sender that never sends.
Reveal solution
use std::sync::mpsc;
use std::thread;
fn fan_in(workers: i32) -> Vec<i32> {
let (tx, rx) = mpsc::channel();
for i in 0..workers {
let tx = tx.clone();
thread::spawn(move || {
tx.send(i * 10).unwrap();
});
}
drop(tx); // drop the last original sender so rx iteration ends
let mut got: Vec<i32> = rx.iter().collect();
got.sort();
got
}