← 中文资源

简体中文版本

recv_timeout 限定通道等待时长

recv_timeout 给阻塞等待设上限:超时返回 RecvTimeoutError 而不是永久挂起,try_recv 只探测一次,两种错误类型都可分支处理。

阅读英文原文

实现说明

recv_timeout 限定通道等待时长的核心是函数 main。 match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。

使用要点

  • 演示输出是带标签的(got:、first try: timed out、sender dropped),每个操作都会留下自己的一行标注。

常见问题

运行「recv_timeout 限定通道等待时长」会打印什么?

运行文件本身,got:、first try: timed out、sender dropped 这些前缀各对应一段演示逻辑。

核心语句

match rx.recv_timeout(Duration::from_millis(1500)) {
    Ok(msg) => println!("got: {msg}"),
    Err(e) => println!("unexpected: {e}"),
}
match rx.recv_timeout(Duration::from_millis(100)) {
    Ok(msg) => println!("got: {msg}"),
    Err(mpsc::RecvTimeoutError::Timeout) => println!("first try: timed out"),
    Err(mpsc::RecvTimeoutError::Disconnected) => println!("sender dropped"),
}
tx.send("late result".into()).unwrap();

代码示例

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

fn main() {
    let (tx, rx) = mpsc::channel::<String>();
    // 克隆一个发送端留在主线程:通道不会因工作线程退出而断开
    let keep_alive = tx.clone();

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(800));
        tx.send("late result".into()).unwrap();
    });

    // recv_timeout:等待有上限,超时返回 RecvTimeoutError 而非永久阻塞
    match rx.recv_timeout(Duration::from_millis(100)) {
        Ok(msg) => println!("got: {msg}"),
        Err(mpsc::RecvTimeoutError::Timeout) => println!("first try: timed out"),
        Err(mpsc::RecvTimeoutError::Disconnected) => println!("sender dropped"),
    }

    // 第二次等待足够长,覆盖慢生产者
    match rx.recv_timeout(Duration::from_millis(1500)) {
        Ok(msg) => println!("got: {msg}"),
        Err(e) => println!("unexpected: {e}"),
    }

    // try_recv 只探测一次,从不等待;发送端仍存活时空队列返回 Empty
    match rx.try_recv() {
        Ok(m) => println!("drained: {m}"),
        Err(mpsc::TryRecvError::Empty) => println!("try_recv: queue empty"),
        Err(mpsc::TryRecvError::Disconnected) => println!("try_recv: channel closed"),
    }

    drop(keep_alive);
}