小编use*_*257的帖子

超时后中止 Rust 中的评估

我有一个 Rust 函数(不是我写的),它要么以毫秒为单位返回,要么在失败前等待约 10 分钟。

我想将对这个函数的调用包装在一个函数中,如果运行时间超过 10 秒,则返回一个Optionwhich is None,如果运行时间较短,则包含结果。然而,我还没有找到任何方法来中断这个函数被调用后的评估。

例如:

// This is the unpredictable function
fn f() {
    // Wait randomly for between 0 and 10 seconds
    let mut rng = rand::thread_rng();
    std::thread::sleep(std::time::Duration::from_secs(rng.gen_range(0, 10)));
}

fn main() {
    for _ in 0..100 {
        // Run f() here but so that the whole loop takes no more than 100 seconds
        // by aborting f() if it takes longer than 1 second
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现了一些可以使用带有超时的 future 的方法,但我想最大程度地减少开销,而且我不确定为该函数的每次调用创建一个 …

timeout rust

6
推荐指数
1
解决办法
2335
查看次数

标签 统计

rust ×1

timeout ×1