#sync #native #events #wait-object

sync-wait-object

同步等待对象(Mutex & CondVar的抽象)

2个不稳定版本

0.2.0 2023年1月22日
0.1.0 2023年1月20日

#165 in Windows API


native-timer 中使用

MIT 协议

20KB
266

基于Mutex和Condvar的等待对象

提供对Rust文档中Condvar提供的Condvar + Mutex使用的抽象。

该库提供三种主要类型:WaitEventManualResetEventAutoResetEvent。其中WaitEvent是提到的核心抽象。ManualResetEventAutoResetEvent是针对bool类型的特殊化。

在Windows平台上编译时,lib还提供了windows模块,用于原生实现ManualResetEventAutoResetEvent

提供的抽象示例

use sync_wait_object::WaitEvent;
use std::thread;

let wait3 = WaitEvent::new_init(0);
let mut wait_handle = wait3.clone();

thread::spawn(move || {
    for i in 1..=3 {
        wait_handle.set_state(i).unwrap();
    }
});

let timeout = std::time::Duration::from_secs(1);
let r#final = *wait3.wait(Some(timeout), |i| *i == 3).unwrap();
let current = *wait3.value().unwrap();
assert_eq!(r#final, 3);
assert_eq!(current, 3);

第二种是等待然后重置值到期望状态。

use sync_wait_object::WaitEvent;
use std::thread;

let wait3 = WaitEvent::new_init(0);
let mut wait_handle = wait3.clone();

thread::spawn(move || {
    for i in 1..=3 {
        wait_handle.set_state(i).unwrap();
    }
});

let timeout = std::time::Duration::from_secs(1);
let r#final = wait3.wait_reset(Some(timeout), || 1, |i| *i == 3).unwrap();
let current = *wait3.value().unwrap();
assert_eq!(r#final, 3);
assert_eq!(current, 1);

依赖项

~0–38MB
~524K SLoC