如何实现超时

时间:2019-05-31 18:12:19

标签: rust timeout

如何在Rust中实现超时以防止等待结果,而在N时间过去之后执行一些其他逻辑,例如,只是为了更精确地说明我要做什么想实现,在Go中我可以使用类似select & time.After的东西:

https://play.golang.org/p/sJum9DANJvR

package main

import "time"

func main() {
    ch := make(chan struct{})

    // run something blocking
    go func() {
        time.Sleep(5 * time.Second)
        ch <- struct{}{}
    }()

    select {
    case <-ch:
        println("task done")

    // timeout after 2 seconds
    case <-time.After(2 * time.Second):
        println("timeout after 2 seconds")
    }
}

这是我对Rust的尝试:

use std::{process::Command, thread, time::Instant};

fn main() {
    let start = Instant::now();

    let task = thread::spawn(|| {
        Command::new("sleep")
            .arg("5")
            .output()
            .expect("failed to execute process");
    });

    // timeout after 2 seconds how ?
    task.join().unwrap();
    println!("{:?}", start.elapsed());
}

但是我在Go中缺少select语句。

在Rust中实现此功能的惯用方式是什么?

在评论的建议链接中,我想到了这一点:

use std::{process::Command, sync::mpsc, thread, time::Duration};

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        match tx.send(
            Command::new("sleep")
                .arg("300")
                .output()
                .expect("failed to execute process"),
        ) {
            Ok(()) => {} //everythin ok
            Err(_) => {} // have been released, don't panic
        }
    });

    let ok = rx.recv_timeout(Duration::from_secs(5));
    println!("{:?}", ok);
}

想知道现在是否要使用mpsc::channel();吗?

0 个答案:

没有答案