-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtimed_rw_lock.rs
More file actions
88 lines (79 loc) · 2.65 KB
/
timed_rw_lock.rs
File metadata and controls
88 lines (79 loc) · 2.65 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use parking_lot::{Mutex, RwLock};
use slog::{warn, Logger};
use std::time::{Duration, Instant};
use crate::prelude::ENV_VARS;
/// Adds instrumentation for timing the performance of the lock.
pub struct TimedRwLock<T> {
id: String,
lock: RwLock<T>,
log_threshold: Duration,
}
impl<T> TimedRwLock<T> {
pub fn new(x: T, id: impl Into<String>) -> Self {
TimedRwLock {
id: id.into(),
lock: RwLock::new(x),
log_threshold: ENV_VARS.lock_contention_log_threshold,
}
}
pub fn write(&self, logger: &Logger) -> parking_lot::RwLockWriteGuard<'_, T> {
loop {
let mut elapsed = Duration::from_secs(0);
match self.lock.try_write_for(self.log_threshold) {
Some(guard) => break guard,
None => {
elapsed += self.log_threshold;
warn!(logger, "Write lock taking a long time to acquire";
"id" => &self.id,
"wait_ms" => elapsed.as_millis(),
);
}
}
}
}
pub fn try_read(&self) -> Option<parking_lot::RwLockReadGuard<'_, T>> {
self.lock.try_read()
}
pub fn read(&self, logger: &Logger) -> parking_lot::RwLockReadGuard<'_, T> {
loop {
let mut elapsed = Duration::from_secs(0);
match self.lock.try_read_for(self.log_threshold) {
Some(guard) => break guard,
None => {
elapsed += self.log_threshold;
warn!(logger, "Read lock taking a long time to acquire";
"id" => &self.id,
"wait_ms" => elapsed.as_millis(),
);
}
}
}
}
}
/// Adds instrumentation for timing the performance of the lock.
pub struct TimedMutex<T> {
id: String,
lock: Mutex<T>,
log_threshold: Duration,
}
impl<T> TimedMutex<T> {
pub fn new(x: T, id: impl Into<String>) -> Self {
TimedMutex {
id: id.into(),
lock: Mutex::new(x),
log_threshold: ENV_VARS.lock_contention_log_threshold,
}
}
pub fn lock(&self, logger: &Logger) -> parking_lot::MutexGuard<'_, T> {
let start = Instant::now();
let guard = self.lock.lock();
let elapsed = start.elapsed();
if elapsed > self.log_threshold {
warn!(logger, "Mutex lock took a long time to acquire";
"id" => &self.id,
"wait_ms" => elapsed.as_millis(),
);
}
guard
}
}