use checkpointkit::{load, save};
use std::sync::Arc;
use tempfile::tempdir;
use std::time::Duration;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn deadlock_test() {
let dir = tempdir().expect("Failed to create temp directory");
let file_path = dir.path().join("deadlock.json");
let path = Arc::new(file_path);
save(&*path, &0).expect("Initial save failed");
let running = Arc::new(AtomicBool::new(true));
let mut handles = vec![];
let p1 = path.clone();
let r1 = running.clone();
handles.push(std::thread::spawn(move || {
while r1.load(Ordering::SeqCst) {
let res = load::<i32>(&*p1).expect("Load failed during deadlock test");
if let Some(val) = res {
save(&*p1, &(val + 1)).expect("Save failed during deadlock test");
}
}
}));
let p2 = path.clone();
let r2 = running.clone();
handles.push(std::thread::spawn(move || {
let mut counter = 0;
while r2.load(Ordering::SeqCst) {
counter += 1;
save(&*p2, &counter).expect("Save failed during deadlock test rapid writes");
}
}));
std::thread::sleep(Duration::from_millis(50));
running.store(false, Ordering::SeqCst);
for handle in handles {
handle.join().expect("Thread panicked or deadlocked");
}
let final_val: Option<i32> = load(&*path).expect("File corrupted after potential deadlock");
assert!(final_val.is_some(), "Final state is missing");
}