Z
ZHANK
编程在线教程Rust 教程Channel 消息传递
并发编程

Channel 消息传递

mpsc::channel 多生产者单消费者、send/recv、迭代接收

Channel 消息传递

Rust 的 mpsc(多生产者单消费者)channel——send 发送所有权,recv 接收。

学完本章你将: 掌握 mpsc::channel、send/recv、迭代接收。


基本用法

rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();  // transmitter, receiver

    thread::spawn(move || {
        tx.send(String::from("Hello")).unwrap();
        tx.send(String::from("World")).unwrap();
        // tx 离开作用域——channel 关闭
    });

    // recv —— 阻塞等待
    let msg = rx.recv().unwrap();
    println!("收到: {}", msg);  // "Hello"

    // 迭代接收——直到 channel 关闭
    for msg in rx {
        println!("收到: {}", msg);  // "World"
    }
}

多生产者

rust
let (tx, rx) = mpsc::channel();
let tx2 = tx.clone();  // 克隆 transmitter

thread::spawn(move || { tx.send("从 tx").unwrap(); });
thread::spawn(move || { tx2.send("从 tx2").unwrap(); });

for msg in rx {
    println!("{}", msg);
}

try_recv —— 非阻塞

rust
match rx.try_recv() {
    Ok(msg) => println!("收到: {}", msg),
    Err(mpsc::TryRecvError::Empty) => println!("暂无消息"),
    Err(mpsc::TryRecvError::Disconnected) => println!("Channel 已关闭"),
}