Skip to content

Commit

Permalink
[refactor] Simplifying and fixing multi-threading test
Browse files Browse the repository at this point in the history
* Using thread.scope in order to get rid of Arc and Barrier
* Fixing assertion to include possible accepted values
  • Loading branch information
didierofrivia committed Jul 31, 2023
1 parent dc98716 commit de07e74
Showing 1 changed file with 10 additions and 25 deletions.
35 changes: 10 additions & 25 deletions limitador/src/storage/atomic_expiring_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ impl Clone for AtomicExpiringValue {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Barrier};
use std::thread;
use std::time::{Duration, SystemTime};

Expand Down Expand Up @@ -130,30 +129,16 @@ mod tests {
#[test]
fn test_overlapping_updates() {
let now = SystemTime::now();
let atomic_expiring_value =
Arc::new(AtomicExpiringValue::new(42, now + Duration::from_secs(10)));

let barrier = Arc::new(Barrier::new(2));

let atomic_expiring_value_clone = Arc::clone(&atomic_expiring_value);
let barrier_clone = Arc::clone(&barrier);
let thread1 = thread::spawn(move || {
barrier_clone.wait();
atomic_expiring_value_clone.update(2, 1, now + Duration::from_secs(11));
});

let atomic_expiring_value_clone2 = Arc::clone(&atomic_expiring_value);
let barrier_clone2 = Arc::clone(&barrier);
let thread2 = thread::spawn(move || {
barrier_clone2.wait();
atomic_expiring_value_clone2.update(1, 1, now);
let atomic_expiring_value = AtomicExpiringValue::new(42, now + Duration::from_secs(10));

thread::scope(|s| {
s.spawn(|| {
atomic_expiring_value.update(1, 1, now);
});
s.spawn(|| {
atomic_expiring_value.update(2, 1, now + Duration::from_secs(11));
});
});

assert_eq!(atomic_expiring_value.value.load(Ordering::SeqCst), 42);

thread2.join().unwrap();
thread1.join().unwrap();

assert_eq!(atomic_expiring_value.value.load(Ordering::SeqCst), 3);
assert!([2i64, 3i64].contains(&atomic_expiring_value.value.load(Ordering::SeqCst)));
}
}

0 comments on commit de07e74

Please sign in to comment.