Mpsc try_recv Polls Multiple Producers
Clone an mpsc Sender so multiple producer threads feed one channel, then poll the receiver with try_recv and handle its Empty and Disconnected outcomes.
Code
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
// 克隆 Sender:多个生产者写同一条通道
let producers: Vec<_> = (0..3)
.map(|id| {
let tx = tx.clone();
thread::spawn(move || {
tx.send(format!("task {id} done")).unwrap();
})
})
.collect();
// 原始 Sender 主动丢弃:全部 Sender 关闭后接收端才会 Disconnected
drop(tx);
// try_recv 不阻塞:Empty 表示暂时没有新消息
let mut received = Vec::new();
while received.len() < 3 {
match rx.try_recv() {
Ok(msg) => received.push(msg),
Err(mpsc::TryRecvError::Empty) => thread::yield_now(),
Err(mpsc::TryRecvError::Disconnected) => break,
}
}
for producer in producers {
producer.join().unwrap();
}
// 排序让打印顺序与消息到达顺序无关
received.sort();
for msg in received {
println!("{msg}");
}
}Step-by-step behavior
Mpsc try_recv Polls Multiple Producers keeps everything in the function main.
The file repeats itself only inside while received.len() < 3. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
Points of care
- No dependencies are listed; the language runtime accounts for all of it.
Using it
Signature: fn main()
Core statements
tx.send(format!("task {id} done")).unwrap();
producer.join().unwrap();
match rx.try_recv() {
Ok(msg) => received.push(msg),
Err(mpsc::TryRecvError::Empty) => thread::yield_now(),
Err(mpsc::TryRecvError::Disconnected) => break,
}
Interactive Tools for This Topic
FAQ
- How do you run Mpsc try_recv Polls Multiple Producers?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.