Skip to content

Commit a8e40d3

Browse files
committed
use Mutex for lock
1 parent 2859eee commit a8e40d3

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

src/processor.rs

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ use crate::matrix::MatrixClient;
33
use crate::webhook::Alert;
44
use crate::{unix_time, AlertId, Result};
55
use actix::prelude::*;
6-
use std::sync::Arc;
7-
use std::sync::atomic::{AtomicBool, Ordering};
6+
use std::sync::{Arc, Mutex};
87
use std::time::Duration;
98

109
const CRON_JOB_INTERVAL: u64 = 5;
@@ -105,8 +104,7 @@ pub struct Processor {
105104
escalation_window: u64,
106105
should_escalate: bool,
107106
// Ensures that only one escalation task is running at the time.
108-
// `true` if locked, `false` if not.
109-
escalation_lock: Arc<AtomicBool>,
107+
escalation_lock: Arc<Mutex<()>>,
110108
}
111109

112110
impl Processor {
@@ -115,7 +113,7 @@ impl Processor {
115113
db: db.map(|db| Arc::new(db)),
116114
escalation_window: escalation_window,
117115
should_escalate: should_escalate,
118-
escalation_lock: Arc::new(AtomicBool::new(false)),
116+
escalation_lock: Default::default(),
119117
}
120118
}
121119
fn db(&self) -> Arc<Database> {
@@ -168,26 +166,23 @@ impl Actor for Processor {
168166
ctx.run_interval(
169167
Duration::from_secs(CRON_JOB_INTERVAL),
170168
move |_proc, _ctx| {
171-
let is_locked = lock.load(Ordering::Relaxed);
169+
// Acquire new handles for async task.
170+
let db = Arc::clone(&db);
171+
let lock = Arc::clone(&lock);
172172

173-
if !is_locked {
174-
// Acquire new handlers for async task.
175-
let db = Arc::clone(&db);
176-
let lock = Arc::clone(&lock);
177-
178-
actix::spawn(async move {
179-
// Seal the escalation lock.
180-
lock.store(true, Ordering::Relaxed);
173+
actix::spawn(async move {
174+
// Immediately exists if the lock cannot be acquired.
175+
if let Ok(locked) = lock.try_lock() {
176+
// Lock acquired and will remain locked until the
177+
// handle goes out of scope.
178+
let _l = locked;
181179

182180
match local(db, escalation_window).await {
183181
Ok(_) => {}
184182
Err(err) => error!("{:?}", err),
185183
}
186-
187-
// Unseal/unlock.
188-
lock.store(false, Ordering::Relaxed);
189-
});
190-
}
184+
}
185+
});
191186
},
192187
);
193188
}

0 commit comments

Comments
 (0)