【Rust】std::sync::mpsc::channel
mpsc是multiple producer, single consumer的缩写。
单生产者示例
use std::sync::mpsc; use std::thread; fn main() { // 多生产者,单消费者通道 let (tx, rx) = mpsc::channel(); // 创建子线程发送数字1 thread::spawn(move || { tx.send(1).unwrap(); }); // 主线程中接收子线程的消息并输出 println!("receive {}", rx.recv().unwrap()); }
多生产者示例
use std::sync::mpsc; use std::thread; fn main() { // 多生产者,单消费者通道 let (tx, rx) = mpsc::channel(); let tx2 = tx.clone(); // 创建线程,发送一个数字1 thread::spawn(move || { tx.send(1).unwrap(); }); // 创建线程,发送一个数字2 thread::spawn(move || { tx2.send(2).unwrap(); }); // 在主线程中接收子线程发送的消息并输出 println!("receive {}", rx.recv().unwrap()); println!("receive {}", rx.recv().unwrap()); }
注意点:
- tx2通过tx1克隆时机,需要在tx 被 move到子线程之前。
- rx.recv()调用1次,取1个消息。 2个子线程发送2个消息,需要调用rx.recv() 2次。
- 主线程收到2个子线程的消息,顺序是随机的。
下一篇:
Rust语言——迭代器和闭包