【问题标题】:What is the Best Way to Drain a mspc channel in Rust?在 Rust 中耗尽 mspc 通道的最佳方法是什么?
【发布时间】:2022-01-21 00:41:56
【问题描述】:

我需要遍历当前存储在接收器中的所有值,然后继续执行程序的其余部分,其实现方式如下:

loop {
    match receiver.recv_timeout(std::time::Duration::from_nanos(0)) {
        Ok(value) => //do stuff with the value,
        _ => break
    }
}

感觉这不是最好/最简单的方法。据我所知,接收器结构中没有'drain'函数,如果接收器中没有更多值,'iter'方法将导致通道暂停当前线程并等待下一个。

这是一个应该如何工作的示例:

use std::sync::mpsc::channel;
use std::thread::spawn;
use std::thread::sleep;


let (sender,receiver) = channel();

spawn(move || {
    for i in 0..1000 {
        sender.send(i).unwrap();
        sleep(std::time::Duration::from_nanos(10));
    }
});

sleep(std::time::Duration::from_millis(1000));

loop {
    match receiver.recv_timeout(std::time::Duration::from_nanos(0)) {
        Ok(value) => {
            println!("received {}", value);
        },
        _ => {
            break;
        },
    }
}
println!("done");

【问题讨论】:

    标签: rust concurrency channel


    【解决方案1】:

    您可以使用try_recvwhile let 来获得更简洁明了的循环:

    while let Ok(value) = receiver.try_recv() {
        println!("received {}", value);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多