use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(8); // capacity 8
// Spawn 3 producers
for i in 0..3 {
let tx = tx.clone();
tokio::spawn(async move {
for j in 0..4 {
tx.send(format!("p{i}-msg{j}")).await.unwrap();
}
});
}
drop(tx); // drop the original — when all clones drop, rx closes
// Single consumer drains until the channel closes
while let Some(msg) = rx.recv().await {
println!("got: {msg}");
}
println!("channel closed");
}
Create a free account and build your private vault. Share publicly whenever you want.