Sub topic 11
Detecting data races in threaded unsafe code
This chapter assumes you know Rust threads, static mut, and the basics of running cargo miri from the earlier chapters. It shows how Miri finds data races and how to fix them.
What a data race is
A data race happens when two threads access the same memory location at the same time, at least one access is a write, and nothing orders the accesses. In Rust, a data race is undefined behavior. Safe Rust rules it out through Send, Sync, and the borrow checker. Unsafe code can break those rules, and static mut is the most common way.
A race often looks harmless natively. COUNTER += 1 on a small integer usually produces a plausible value, so a test passes. Miri tracks which accesses are ordered by synchronization, so it can report the race even when the native result looks correct.
A racing program
Two threads write to the same static mut with no synchronization:
use std::thread;
static mut COUNTER: u32 = 0;
fn main() {
let h = thread::spawn(|| unsafe {
COUNTER += 1;
});
unsafe {
COUNTER += 1;
}
h.join().unwrap();
}Run it with cargo +nightly miri run. Miri reports an error that says "Data race detected between (1) non-atomic write on thread main and (2) non-atomic write on thread <unnamed>". The report points to both accesses. Read both locations, because the fix usually involves both.
Newer compilers may also warn about references to static mut. That warning is separate from the Miri error.
How Miri finds races
Miri uses a happens-before model. Each thread keeps a vector clock, which records the latest operation of every other thread that it is known to have seen. Synchronization operations such as join, mutex locks, channel messages, and atomic operations with acquire or release ordering transfer clock information between threads. When a thread accesses memory, Miri checks that the previous conflicting access happened before it. If it did not, Miri reports a race.
Note that spawn does create an ordering edge, but only for operations before the spawn. Work after the spawn is unordered with respect to the new thread until a join or another synchronization point.
Schedules and seeds
Races depend on how threads interleave. Miri chooses a schedule, and the race detector flags accesses that are unordered even if this run happened to execute them one after the other. You can still vary the schedule to explore different behaviors, which matters for code that depends on atomics and weak memory.
MIRIFLAGS="-Zmiri-seed=1" cargo +nightly miri test
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test-Zmiri-seed fixes the random seed so a failure is reproducible. -Zmiri-many-seeds runs the program once per seed in the range and stops at the first failure.
Fixing the race
Replace the unsynchronized access with an atomic, which is safe and needs no unsafe:
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn main() {
let h = thread::spawn(|| {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
COUNTER.fetch_add(1, Ordering::Relaxed);
h.join().unwrap();
assert_eq!(COUNTER.load(Ordering::Relaxed), 2);
}Use a Mutex when the shared data is more than a single integer. If you must keep unsafe, make sure that every access is ordered by a lock, a join, or acquire and release operations.
Common mistakes
- Using
Ordering::Relaxedto publish data. Relaxed operations are atomic but create no happens-before edge, so a non-atomic read of data written before the store can still race. - Assuming a passing run means no races. Miri only checks the interleavings it explores.
- Wrapping a type in a struct and implementing
unsafe impl Syncwithout checking that every method is race-free.
Exercise
Why does Miri report a race for two non-atomic writes to COUNTER even if the program prints the expected result natively?
Show answer
Miri checks for a happens-before relationship between conflicting accesses, not for a visibly wrong result. Two unsynchronized writes to the same location from different threads have no such ordering, so they are a data race and undefined behavior, even if the native output looks correct.
Exercise
Which command runs your tests under 16 different schedules?
Show answer
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test