当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust WaitTimeoutResult.timed_out用法及代码示例


本文简要介绍rust语言中 std::sync::WaitTimeoutResult.timed_out 的用法。

用法

pub fn timed_out(&self) -> bool

如果已知等待已超时,则返回 true

例子

此示例生成一个线程,该线程将更新布尔值,然后在通知 condvar 之前等待 100 毫秒。

主线程将在 condvar 上等待超时,然后在布尔值更新并通知后离开。

use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;

let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);

thread::spawn(move || {
    let (lock, cvar) = &*pair2;

    // Let's wait 20 milliseconds before notifying the condvar.
    thread::sleep(Duration::from_millis(20));

    let mut started = lock.lock().unwrap();
    // We update the boolean value.
    *started = true;
    cvar.notify_one();
});

// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
loop {
    // Let's put a timeout on the condvar's wait.
    let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
    // 10 milliseconds have passed, or maybe the value changed!
    started = result.0;
    if *started == true {
        // We received the notification and the value has been updated, we can leave.
        break
    }
}

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::sync::WaitTimeoutResult.timed_out。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。