mpsc 通道 ​

核心概念 ​

mpsc 是 Rust 标准库中的消息传递通道,全称是 Multi-Producer, Single-Consumer(多生产者,单消费者)。通道由 mpsc::channel() 创建,返回一对 (Sender<T>, Receiver<T>)。Sender 可以 clone 出多个生产者,但 Receiver 只有一个消费者。通道是线程间传递数据的主要手段之一,遵循 Rust 的"通过通信来共享内存"的理念,而不是"通过共享内存来通信"。通道传递的数据类型 T 必须满足 Send trait。

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

fn main() {
    // 创建通道:tx 是发送端,rx 是接收端
    let (tx, rx) = mpsc::channel();

    // 在子线程中发送数据
    thread::spawn(move || {
        tx.send("来自子线程的消息").unwrap();
        println!("消息已发送");
    });

    // 在主线程中接收数据
    let msg = rx.recv().unwrap();
    println!("收到: {}", msg);
}

通道的发送和接收 ​

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

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

    thread::spawn(move || {
        let messages = vec!["第一条", "第二条", "第三条", "第四条", "第五条"];
        for msg in messages {
            tx.send(msg).unwrap();
            println!("发送: {}", msg);
            thread::sleep(Duration::from_millis(100));
        }
        println!("所有消息发送完毕");
        // tx 在这里被 drop,通道关闭
    });

    // recv() 阻塞等待消息
    // 当所有 Sender 被 drop 后,recv 返回 Err
    loop {
        match rx.recv() {
            Ok(msg) => println!("接收: {}", msg),
            Err(_) => {
                println!("通道已关闭");
                break;
            }
        }
    }
}

recv 的三种方式 ​

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

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

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(200));
        tx.send("延迟消息").unwrap();
    });

    // === recv():阻塞等待 ===
    // 一直等到收到消息或通道关闭
    let msg = rx.recv().unwrap();
    println!("recv: {}", msg);

    // === try_recv():非阻塞 ===
    let (tx2, rx2) = mpsc::channel();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(200));
        tx2.send("延迟消息2").unwrap();
    });

    // 立即返回,不等待
    match rx2.try_recv() {
        Ok(msg) => println!("try_recv 收到: {}", msg),
        Err(mpsc::TryRecvError::Empty) => println!("try_recv: 暂无消息"),
        Err(mpsc::TryRecvError::Disconnected) => println!("try_recv: 通道关闭"),
    }

    // 等一会再试
    thread::sleep(Duration::from_millis(300));
    match rx2.try_recv() {
        Ok(msg) => println!("try_recv 收到: {}", msg),
        Err(e) => println!("try_recv: {:?}", e),
    }

    // === recv_timeout():带超时的阻塞 ===
    let (tx3, rx3) = mpsc::channel();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(500));
        let _ = tx3.send("很晚的消息");
    });

    match rx3.recv_timeout(Duration::from_millis(200)) {
        Ok(msg) => println!("recv_timeout 收到: {}", msg),
        Err(mpsc::RecvTimeoutError::Timeout) => println!("recv_timeout: 超时了"),
        Err(mpsc::RecvTimeoutError::Disconnected) => println!("recv_timeout: 通道关闭"),
    }
}
方法阻塞返回适用场景
recv()阻塞直到有消息Result<T, RecvError>必须等待结果
try_recv()不阻塞Result<T, TryRecvError>轮询检查
recv_timeout(d)最多阻塞 d 时间Result<T, RecvTimeoutError>有时间限制的等待

用 for 循环遍历通道 ​

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

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

    thread::spawn(move || {
        for i in 1..=5 {
            tx.send(format!("消息 #{}", i)).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
        // tx drop 后通道关闭,for 循环自动结束
    });

    // Receiver 实现了 IntoIterator
    // for 循环会一直接收直到通道关闭
    println!("开始接收:");
    for msg in rx {
        println!("  收到: {}", msg);
    }
    println!("通道已关闭,循环结束");
}

send 失败的处理 ​

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

fn main() {
    let (tx, rx) = mpsc::channel::<String>();

    // 提前 drop 接收端
    drop(rx);

    // 发送到已关闭的通道会失败
    match tx.send("消息".to_string()) {
        Ok(()) => println!("发送成功"),
        Err(e) => println!("发送失败: {} (接收端已关闭)", e),
    }

    // 实际场景:接收端可能在任何时候关闭
    let (tx, rx) = mpsc::channel();

    let producer = thread::spawn(move || {
        for i in 0..100 {
            match tx.send(i) {
                Ok(()) => {}
                Err(_) => {
                    println!("生产者: 接收端已关闭,在第 {} 条时停止", i);
                    return;
                }
            }
            thread::sleep(Duration::from_millis(10));
        }
    });

    // 接收 5 条后就关闭
    for _ in 0..5 {
        if let Ok(val) = rx.recv() {
            println!("收到: {}", val);
        }
    }
    drop(rx);  // 关闭接收端
    println!("接收端已关闭");

    producer.join().unwrap();
}

基本示例 ​

用 mpsc 通道构建一个任务分发系统:

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

#[derive(Debug)]
enum Command {
    Process(String),       // 处理数据
    Status,                // 查询状态
    Shutdown,              // 关闭
}

#[derive(Debug)]
enum Response {
    Done(String),          // 处理完成
    StatusReport(usize),   // 状态报告
}

fn main() {
    // 命令通道:主线程 → 工作线程
    let (cmd_tx, cmd_rx) = mpsc::channel::<Command>();
    // 响应通道:工作线程 → 主线程
    let (resp_tx, resp_rx) = mpsc::channel::<Response>();

    // 工作线程
    let worker = thread::spawn(move || {
        let mut processed = 0;

        for cmd in cmd_rx {
            match cmd {
                Command::Process(data) => {
                    // 模拟处理
                    thread::sleep(Duration::from_millis(50));
                    processed += 1;
                    let result = format!("处理完成: '{}' (第{}个)", data, processed);
                    resp_tx.send(Response::Done(result)).unwrap();
                }
                Command::Status => {
                    resp_tx.send(Response::StatusReport(processed)).unwrap();
                }
                Command::Shutdown => {
                    println!("工作线程: 收到关闭命令,共处理 {} 个任务", processed);
                    break;
                }
            }
        }
    });

    // 主线程发送命令
    let tasks = vec!["数据A", "数据B", "数据C", "数据D", "数据E"];

    for task in &tasks {
        cmd_tx.send(Command::Process(task.to_string())).unwrap();
    }

    // 查询状态
    cmd_tx.send(Command::Status).unwrap();

    // 接收所有响应
    for _ in 0..(tasks.len() + 1) {
        match resp_rx.recv().unwrap() {
            Response::Done(msg) => println!("  {}", msg),
            Response::StatusReport(count) => println!("  状态: 已处理 {} 个", count),
        }
    }

    // 关闭
    cmd_tx.send(Command::Shutdown).unwrap();
    worker.join().unwrap();

    // === 流水线模式 ===
    println!("\n=== 流水线 ===");
    let (tx1, rx1) = mpsc::channel();
    let (tx2, rx2) = mpsc::channel();
    let (tx3, rx3) = mpsc::channel();

    // 阶段1:生成数据
    thread::spawn(move || {
        for i in 1..=5 {
            tx1.send(i).unwrap();
        }
    });

    // 阶段2:翻倍
    thread::spawn(move || {
        for val in rx1 {
            tx2.send(val * 2).unwrap();
        }
    });

    // 阶段3:格式化
    thread::spawn(move || {
        for val in rx2 {
            tx3.send(format!("结果: {}", val)).unwrap();
        }
    });

    // 收集最终结果
    for result in rx3 {
        println!("  {}", result);
    }
}

常见问题 ​

问题一:mpsc 通道有容量限制吗?

mpsc::channel() 创建的是无界通道,缓冲区会根据需要自动增长。如果发送速度远大于接收速度,内存会持续增长。需要有界通道用 mpsc::sync_channel(n)。

问题二:通道什么时候关闭?

当所有 Sender 被 drop 时,通道的发送端关闭,recv() 返回 Err。当 Receiver 被 drop 时,通道的接收端关闭,send() 返回 Err。

问题三:通道可以传递引用吗?

通常不行。通道要求 T: Send,而非 'static 的引用不满足。可以传递拥有所有权的数据(String、Vec 等),或者用 Arc 共享数据。

问题四:通道和共享内存(Mutex)怎么选?

通道适合"任务分发"和"消息传递"模式,数据所有权从发送方转移到接收方。Mutex 适合多个线程读写同一份数据。通道更安全、更容易推理,Mutex 更灵活但容易出错。

适用场景 ​

  • 线程间通信:在不同线程之间传递数据
  • 任务分发:主线程分发任务给工作线程
  • 流水线:多阶段数据处理管道
  • 事件通知:一个线程通知另一个线程发生了事件

注意事项 ​

  • mpsc::channel() 创建无界通道,可能导致内存无限增长
  • Sender 可以 clone(多生产者),Receiver 不能(单消费者)
  • 通道传递数据的所有权,发送后发送方不再拥有
  • send 和 recv 都返回 Result,需要处理错误
  • Receiver 实现了 IntoIterator,可以用 for 循环遍历
  • 通道中的数据类型 T 必须实现 Send

总结 ​

mpsc::channel() 创建多生产者、单消费者的无界通道,返回 (Sender<T>, Receiver<T>)。Sender 可以 clone 支持多个生产者,Receiver 只有一个。send() 发送数据的所有权,recv() 阻塞等待接收。try_recv() 非阻塞,recv_timeout() 带超时。当所有 Sender 被 drop 时通道关闭,recv 返回 Err。Receiver 实现了 IntoIterator,可以用 for 循环持续接收直到通道关闭。通道适合线程间消息传递、任务分发和流水线模式。