Skip to content

Commit

Permalink
use loom for concurrency testing
Browse files Browse the repository at this point in the history
  • Loading branch information
CJP10 committed Aug 18, 2024
1 parent db162d6 commit 45a43de
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ license = "MIT/Apache-2.0"
[dependencies]
parking_lot = "0.12.3"

[target.'cfg(loom)'.dependencies]
loom = "0.7"

[dev-dependencies]
criterion = "0.5.1"
criterion-plot = "0.5.0"
Expand Down
47 changes: 42 additions & 5 deletions src/experimental.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ use std::{
iter::FromIterator,
mem::ManuallyDrop,
ops::{Deref, DerefMut},
sync::atomic::{
AtomicU64,
Ordering::{Acquire, Relaxed, Release},
},
sync::atomic::Ordering::{Acquire, Relaxed, Release},
};

#[cfg(not(loom))]
use std::sync::atomic::AtomicU64;

#[cfg(loom)]
use loom::sync::atomic::AtomicU64;

const U64_BITS: usize = u64::BITS as usize;

pub struct Pool<T> {
Expand Down Expand Up @@ -139,7 +142,6 @@ impl AtomicBitSet {
#[cfg(test)]
mod tests {
use crate::experimental::Pool;
use std::iter::FromIterator;
use std::sync::atomic::Ordering::Relaxed;

#[test]
Expand Down Expand Up @@ -191,3 +193,38 @@ mod tests {
}
}
}

#[cfg(loom)]
mod loom_tests {
use crate::experimental::Pool;
use loom::sync::Arc;

#[test]
fn concurrent_pull_sum() {
loom::model(|| {
const N: usize = 2;
let p: Pool<usize> = (0..N).map(|_| 0).collect();
let p = Arc::new(p);

let handles: Vec<_> = (0..N)
.map(|_| {
let p1 = p.clone();
loom::thread::spawn(move || {
*p1.pull().unwrap() += 1;
})
})
.collect();

for handle in handles {
handle.join().unwrap();
}

unsafe {
assert_eq!(
p.objects.iter().map(|x| (*x.get()).unwrap()).sum::<usize>(),
N
);
}
});
}
}

0 comments on commit 45a43de

Please sign in to comment.