Sub topic 3
Detecting Data Races in Threaded Unsafe Rust
Assume you know Rust ownership, borrowing, lifetimes, basic Cargo commands, raw pointers, unsafe, and rustup. This chapter focuses on how Miri checks threaded unsafe code and how to act on its findings.
Finding a Data Race
A data race occurs when threads access the same memory concurrently, at least one access writes, and there is no synchronization. The behavior is undefined, even if the program appears to print the expected result.
use std::thread;
static mut COUNTER: u32 = 0;
fn main() {
let handle = thread::spawn(|| unsafe {
COUNTER += 1;
});
unsafe {
COUNTER += 1;
}
handle.join().unwrap();
}Run this with Miri:
cargo +nightly miri runMiri can report a data race when the interpreter observes conflicting accesses. Use different schedules to explore different interleavings:
MIRIFLAGS="-Zmiri-seed=1" cargo +nightly miri runA seed changes the pseudo-random scheduling choices. Testing several seeds increases coverage, but it does not examine every possible schedule.
Fixing What Miri Finds
Replace unsynchronized shared mutation with a synchronization primitive. An atomic operation is suitable for a simple counter:
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn main() {
let handle = thread::spawn(|| {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
COUNTER.fetch_add(1, Ordering::Relaxed);
handle.join().unwrap();
assert_eq!(COUNTER.load(Ordering::Relaxed), 2);
}Use a Mutex when several values must change together. Miri can then verify that the synchronization is used consistently.
> callout note > Miri reports races and other undefined behavior along executed paths. It does not prove that unexecuted paths are safe.
Miri-Friendly Tests and CI
Keep Miri tests deterministic and small. Miri is much slower than native execution, so reduce stress-test workloads under cfg(miri) and avoid unnecessary sleeps or huge loops. Run both ordinary tests and Miri tests:
cargo test
cargo +nightly miri testIn continuous integration, install the nightly component and run Miri as a separate job. Pinning a nightly toolchain can make results more reproducible.
Limits of a Clean Run
A clean run means Miri found no supported problem in the code paths and schedules it examined. It does not detect every logic error, every platform-specific problem, or all behavior involving unsupported foreign-function interfaces. It also cannot prove that another input or thread schedule is safe.
Exercise
Why does a clean Miri run not prove that a threaded program has no data races?
Show answer
Miri checks only the executions and schedules it explores, so untested paths or interleavings may still contain races.