基于 CSP 模型的 MPSC 消息通道通信,探讨 Send 与 Sync 特征如何从类型系统层面防止数据在线程间非法传递。
1. 多生产者单消费者 (MPSC) 通道
“不要通过共享内存来通信,而要通过通信来共享内存”:
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hello from worker");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("主线程收到消息: {}", received);
}