use loom::cell::UnsafeCell;
use loom::sync::Arc;
use loom::sync::atomic::{AtomicU32, Ordering, fence};
use loom::thread;
const SLOTS: usize = 3;
const SEAL: u32 = u32::MAX;
struct Journal {
commit: [AtomicU32; SLOTS],
body: [UnsafeCell<u32>; SLOTS],
}
impl Journal {
fn new() -> Journal {
Journal {
commit: std::array::from_fn(|_| AtomicU32::new(0)),
body: std::array::from_fn(|_| UnsafeCell::new(0)),
}
}
fn append(&self, slot: usize, value: u32) {
self.body[slot].with_mut(|p| unsafe { *p = value });
self.commit[slot].store(value, Ordering::Release);
}
fn seal(&self, slot: usize) {
self.commit[slot].store(SEAL, Ordering::Release);
}
fn read(&self, slot: usize) -> Option<u32> {
let word = self.commit[slot].load(Ordering::Relaxed);
if word == 0 {
return None;
}
fence(Ordering::Acquire);
if word == SEAL {
return Some(SEAL);
}
let body = self.body[slot].with(|p| unsafe { *p });
assert_eq!(body, word, "reader saw a commit word without its body");
Some(body)
}
}
#[test]
fn reader_never_sees_unpublished_bodies() {
loom::model(|| {
let j = Arc::new(Journal::new());
let w = {
let j = j.clone();
thread::spawn(move || {
j.append(0, 11);
j.append(1, 22);
j.seal(2);
})
};
let mut slot = 0;
let mut seen = Vec::new();
while slot < SLOTS {
match j.read(slot) {
Some(SEAL) => break,
Some(v) => {
seen.push(v);
slot += 1;
}
None => thread::yield_now(),
}
}
assert_eq!(seen, [11, 22]);
w.join().unwrap();
});
}
#[test]
fn two_readers_agree() {
loom::model(|| {
let j = Arc::new(Journal::new());
let w = {
let j = j.clone();
thread::spawn(move || {
j.append(0, 7);
j.append(1, 8);
})
};
let r = {
let j = j.clone();
thread::spawn(move || [j.read(0), j.read(1)])
};
let mine = [j.read(0), j.read(1)];
let theirs = r.join().unwrap();
w.join().unwrap();
for got in [mine, theirs] {
assert!(got[0].is_none_or(|v| v == 7));
assert!(got[1].is_none_or(|v| v == 8));
}
});
}