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
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
pub struct MutexWithTimeout<T> {
inner: Mutex<T>,
timeout: Duration,
}
impl<T> MutexWithTimeout<T> {
pub fn new(inner: T, timeout: Duration) -> Self {
Self {
inner: Mutex::new(inner),
timeout,
}
}
pub fn lock(&self) -> Option<MutexGuard<T>> {
let start = std::time::Instant::now();
loop {
if let Ok(guard) = self.inner.try_lock() {
return Some(guard);
}
if start.elapsed() > self.timeout {
break;
}
}
None
}
pub fn try_lock(&self) -> Option<std::sync::MutexGuard<T>> {
self.inner.try_lock().ok()
}
}