agentmux_srv_core/backend/blockcontroller/
resync_lock.rs1use std::collections::HashSet;
10use std::sync::{Condvar, Mutex};
11
12static BUSY: Mutex<Option<HashSet<String>>> = Mutex::new(None);
13static FREED: Condvar = Condvar::new();
14
15pub(super) struct ResyncGuard(String);
17
18impl ResyncGuard {
19 pub(super) fn acquire(block_id: &str) -> Self {
20 let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
21 while busy.get_or_insert_with(HashSet::new).contains(block_id) {
22 busy = FREED.wait(busy).unwrap_or_else(|e| e.into_inner());
23 }
24 busy.get_or_insert_with(HashSet::new).insert(block_id.to_string());
25 Self(block_id.to_string())
26 }
27}
28
29impl Drop for ResyncGuard {
30 fn drop(&mut self) {
31 let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
32 if let Some(set) = busy.as_mut() {
33 set.remove(&self.0);
34 }
35 FREED.notify_all();
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42 use std::sync::atomic::{AtomicUsize, Ordering};
43 use std::sync::Arc;
44
45 #[test]
46 fn two_resyncs_of_one_block_never_overlap_and_two_blocks_do() {
47 let (inside, worst) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
48 let threads: Vec<_> = (0..8)
49 .map(|_| {
50 let (inside, worst) = (inside.clone(), worst.clone());
51 std::thread::spawn(move || {
52 let _g = ResyncGuard::acquire("resync-lock-same");
53 let now = inside.fetch_add(1, Ordering::SeqCst) + 1;
54 worst.fetch_max(now, Ordering::SeqCst);
55 std::thread::sleep(std::time::Duration::from_millis(5));
56 inside.fetch_sub(1, Ordering::SeqCst);
57 })
58 })
59 .collect();
60 threads.into_iter().for_each(|t| t.join().unwrap());
61 assert_eq!(worst.load(Ordering::SeqCst), 1, "one block, one resync at a time");
62
63 let held = ResyncGuard::acquire("resync-lock-a");
65 let other = std::thread::spawn(|| drop(ResyncGuard::acquire("resync-lock-b")));
66 other.join().unwrap();
67 drop(held);
68 drop(ResyncGuard::acquire("resync-lock-a")); }
70}