← 中文资源

简体中文版本

Condvar Wait 超时截止

用 Condvar::wait_timeout_while 给条件等待加截止时间:通知到达或超时都会返回,没有通知时不会把线程挂死。

阅读英文原文

实现说明

Condvar Wait 超时截止以函数 main为骨架。

使用要点

  • 跑完文件,输出里会留下标记——notified:、timed out:。

常见问题

运行「Condvar Wait 超时截止」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 notified:、timed out: 这类标签。

核心语句

let ready = lock.lock().unwrap();
let guard = lock.lock().unwrap();

代码示例

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

fn main() {
    let state = Arc::new((Mutex::new(false), Condvar::new()));

    let waiter = {
        let state = Arc::clone(&state);
        thread::spawn(move || {
            let (lock, condvar) = &*state;
            let ready = lock.lock().unwrap();
            // wait_timeout_while returns on notification or deadline
            let (guard, result) = condvar
                .wait_timeout_while(ready, Duration::from_millis(50), |ready| !*ready)
                .unwrap();
            (*guard, result.timed_out())
        })
    };

    thread::sleep(Duration::from_millis(10));
    {
        let (lock, condvar) = &*state;
        *lock.lock().unwrap() = true;
        condvar.notify_one();
    }
    println!("notified: {:?}", waiter.join().unwrap());

    // without a notification the same wait reports a timeout
    let lone = Arc::new((Mutex::new(false), Condvar::new()));
    let (lock, condvar) = &*lone;
    let guard = lock.lock().unwrap();
    let (_guard, result) = condvar
        .wait_timeout_while(guard, Duration::from_millis(10), |ready| !*ready)
        .unwrap();
    println!("timed out: {}", result.timed_out());
}