Skip to content

Commit

Permalink
Fix data race tests to work with weak memory
Browse files Browse the repository at this point in the history
  • Loading branch information
cbeuw committed May 7, 2022
1 parent acf696b commit c0be33b
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions tests/run-pass/concurrency/data_race.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


use std::sync::atomic::{AtomicUsize, fence, Ordering};
use std::thread::spawn;
use std::thread::{spawn, yield_now};

#[derive(Copy, Clone)]
struct EvilSend<T>(pub T);
Expand All @@ -12,6 +12,21 @@ unsafe impl<T> Sync for EvilSend<T> {}

static SYNC: AtomicUsize = AtomicUsize::new(0);

// Spins and yields until until acquires a pre-determined value
fn acquires_value(loc: &AtomicUsize, val: usize) -> usize {
while loc.load(Ordering::Acquire) != val {
yield_now();
}
val
}

fn reads_value(loc: &AtomicUsize, val: usize) -> usize {
while loc.load(Ordering::Relaxed) != val {
yield_now();
}
val
}

fn test_fence_sync() {
let mut var = 0u32;
let ptr = &mut var as *mut u32;
Expand All @@ -25,12 +40,9 @@ fn test_fence_sync() {
});

let j2 = spawn(move || {
if SYNC.load(Ordering::Relaxed) == 1 {
fence(Ordering::Acquire);
unsafe { *evil_ptr.0 }
} else {
0
}
reads_value(&SYNC, 1);
fence(Ordering::Acquire);
unsafe { *evil_ptr.0 }
});

j1.join().unwrap();
Expand Down Expand Up @@ -69,23 +81,20 @@ pub fn test_rmw_no_block() {
});

let j2 = spawn(move || {
if SYNC.swap(2, Ordering::Relaxed) == 1 {
while SYNC.swap(2, Ordering::Relaxed) != 1 {
//No op, blocking store removed
}
});

let j3 = spawn(move || {
if SYNC.load(Ordering::Acquire) == 2 {
*c.0
} else {
0
}
acquires_value(&SYNC, 2);
*c.0
});

j1.join().unwrap();
j2.join().unwrap();
let v = j3.join().unwrap();
assert!(v == 1 || v == 2);
assert!(v == 1);
}
}

Expand All @@ -101,11 +110,8 @@ pub fn test_simple_release() {
});

let j2 = spawn(move || {
if SYNC.load(Ordering::Acquire) == 1 {
*c.0
} else {
0
}
acquires_value(&SYNC, 1);
*c.0
});

j1.join().unwrap();
Expand Down

0 comments on commit c0be33b

Please sign in to comment.