在 Rust 中耗尽 mspc 通道的最佳方法是什么?

What is the Best Way to Drain a mspc channel in Rust?

我需要遍历当前存储在接收器中的所有值,然后继续程序的其余部分,它是这样实现的:

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");

您可以使用try_recvwhile let以获得更简洁和更清晰的循环:

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