當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。