use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
// Three producers — clone tx for each
for i in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
for j in 0..3 {
tx.send(format!("from {i}: msg {j}")).unwrap();
thread::sleep(Duration::from_millis(10));
}
});
}
drop(tx); // close the original — receiver loop ends when all clones drop
for msg in rx { // iterator form — yields until channel closes
println!("got: {msg}");
}
println!("done");
}
Create a free account and build your private vault. Share publicly whenever you want.