从通道读取还是超时?

12

我想在Rust 1.9中从mpsc::channel 超时读取,有没有明确的习语可以使这个工作?我见过mpsc::Select中描述的不稳定方法,但是这个Github讨论表明这不是一个健壮的方法。有没有更好的推荐方法来实现接收或超时语义?

3个回答

9
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!");
}

5

我不知道如何使用标准库通道来实现,但是chan crate提供了一个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!");
        },
    }
}

0

我能够使用标准库使某些东西工作。

use std::sync::mpsc::channel;
use std::thread;
use std::time::{Duration, Instant};
use std::sync::mpsc::TryRecvError;


fn main() {
    let (send, recv) = channel();

    thread::spawn(move || {
        send.send("Hello world!").unwrap();
        thread::sleep(Duration::from_secs(1)); // block for two seconds
        send.send("Delayed").unwrap();
    });

    println!("{}", recv.recv().unwrap()); // Received immediately
    println!("Waiting...");

    let mut resolved: bool = false;
    let mut result: Result<&str, TryRecvError> = Ok("Null");

    let now = Instant::now();
    let timeout: u64= 2;

    while !resolved {
        result = recv.try_recv();
        resolved = !result.is_err();
        if now.elapsed().as_secs() as u64 > timeout {
            break;
        }
    }

    if result.is_ok(){
        println!("Results: {:?}", result.unwrap());
    }

    println!("Time elapsed: {}", now.elapsed().as_secs());
    println!("Resolved: {}", resolved.to_string());
}

这将会旋转timeout秒,并且将会返回接收到的值或者一个错误结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接