-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync.rs
56 lines (47 loc) · 1.59 KB
/
sync.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::{
result::Result,
sync::{Arc, Mutex},
time::Duration,
};
use situwaition::{wait_for, SyncSituwaition};
use thiserror::Error;
#[derive(Debug, Error)]
enum ExampleError {
#[error("not done counting yet")]
NotDoneCountingError,
#[error("mutex encounted a poison error")]
MutexPoisonError,
}
// This example uses wait_for to wait for a value that changes, completely synchronously.
//
// By default, wait_for checks every 250ms, and times out after 3 seconds.
// this means the code below should wait 750ms in total, and value should never be above 3.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let value = Arc::new(Mutex::new(0));
let shared_value = value.clone();
eprintln!("finished setup");
let result = wait_for(move || {
// Get the current value from the mutex
let mut current_value = shared_value
.lock()
.map_err(|_| ExampleError::MutexPoisonError)?;
// Act on the current value
eprintln!("acting on unlocked value... {current_value}");
if *current_value >= 3 {
Ok(42)
} else {
*current_value += 1;
Err(ExampleError::NotDoneCountingError)
}
})?;
assert!(matches!(result, 42));
eprintln!("resulting value is: {}", result);
// Synchronous wait
let result = situwaition::sync::SyncWaiter::with_timeout(
|| Err(ExampleError::NotDoneCountingError) as Result<(), ExampleError>,
Duration::from_millis(500),
)?
.exec();
eprintln!("synchronous always-failling result: {:?}", result);
Ok(())
}