2020-12-07 12:16:06 -06:00
|
|
|
// ignore-windows: Concurrency on Windows is not supported yet.
|
|
|
|
|
|
|
|
use std::thread::spawn;
|
|
|
|
use std::ptr::null_mut;
|
|
|
|
use std::sync::atomic::{Ordering, AtomicPtr};
|
2020-12-09 07:35:42 -06:00
|
|
|
use std::mem::MaybeUninit;
|
2020-12-07 12:16:06 -06:00
|
|
|
|
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
struct EvilSend<T>(pub T);
|
|
|
|
|
|
|
|
unsafe impl<T> Send for EvilSend<T> {}
|
|
|
|
unsafe impl<T> Sync for EvilSend<T> {}
|
|
|
|
|
|
|
|
pub fn main() {
|
|
|
|
// Shared atomic pointer
|
2020-12-09 07:35:42 -06:00
|
|
|
let pointer = AtomicPtr::new(null_mut::<MaybeUninit<usize>>());
|
|
|
|
let ptr = EvilSend(&pointer as *const AtomicPtr<MaybeUninit<usize>>);
|
2020-12-07 12:16:06 -06:00
|
|
|
|
|
|
|
// Note: this is scheduler-dependent
|
|
|
|
// the operations need to occur in
|
|
|
|
// order, otherwise the allocation is
|
|
|
|
// not visible to the other-thread to
|
|
|
|
// detect the race:
|
|
|
|
// 1. alloc
|
|
|
|
// 2. write
|
|
|
|
unsafe {
|
|
|
|
let j1 = spawn(move || {
|
2020-12-07 13:10:01 -06:00
|
|
|
// Concurrent allocate the memory.
|
|
|
|
// Uses relaxed semantics to not generate
|
|
|
|
// a release sequence.
|
2020-12-07 12:16:06 -06:00
|
|
|
let pointer = &*ptr.0;
|
2020-12-09 07:35:42 -06:00
|
|
|
pointer.store(Box::into_raw(Box::new(MaybeUninit::uninit())), Ordering::Relaxed);
|
2020-12-07 12:16:06 -06:00
|
|
|
});
|
|
|
|
|
|
|
|
let j2 = spawn(move || {
|
|
|
|
let pointer = &*ptr.0;
|
2020-12-07 17:18:57 -06:00
|
|
|
|
2020-12-09 07:35:42 -06:00
|
|
|
// Note: could also error due to reading uninitialized memory, but the data-race detector triggers first.
|
|
|
|
*pointer.load(Ordering::Relaxed) //~ ERROR Data race detected between Read on Thread(id = 2) and Allocate on Thread(id = 1)
|
2020-12-07 12:16:06 -06:00
|
|
|
});
|
|
|
|
|
|
|
|
j1.join().unwrap();
|
|
|
|
j2.join().unwrap();
|
|
|
|
|
|
|
|
// Clean up memory, will never be executed
|
|
|
|
drop(Box::from_raw(pointer.load(Ordering::Relaxed)));
|
|
|
|
}
|
|
|
|
}
|