从频道读取还是超时?

Bos*_*osh 8 multithreading channels rust

使用Rust 1.9,我想读取mpsc::channel 超时.是否有明确的习惯使这项工作?我已经看到了描述的不稳定方法,mpsc::Select但是这个Github讨论表明它不是一种强有力的方法.是否有更好的推荐方式来实现接收或超时语义?

She*_*ter 5

我不知道你会如何与标准库的渠道去做,但陈箱提供了一个chan_select!宏:

#[macro_use]
extern crate chan;

use std::time::Duration;

fn main() {
    let (_never_sends, never_receives) = chan::sync::<bool>(1);
    let timeout = chan::after(Duration::from_millis(50));

    chan_select! {
        timeout.recv() => {
            println!("timed out!");
        },
        never_receives.recv() => {
            println!("Shouldn't have a value!");
        },
    }
}
Run Code Online (Sandbox Code Playgroud)


tez*_*tez 5

Rust 1.12 引入Receiver::recv_timeout

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

fn main() {
    let (.., rx) = channel::<bool>();
    let timeout = Duration::new(3, 0);

    println!("start recv");
    let _ = rx.recv_timeout(timeout);
    println!("done!");
}
Run Code Online (Sandbox Code Playgroud)