Sub topic 11
Detecting data races in threaded unsafe code
This chapter assumes you know Rust threads (thread::spawn, join), the basics of Arc, Mutex and atomics, and how to run cargo miri test and read a Miri report from earlier chapters. Here you will learn what Miri counts as a data race, how it finds one, and how to fix and reproduce races.
What counts as a data race
A data race is two memory accesses that meet all of these conditions:
- They touch the same memory location.
- They happen on different threads.
- At least one of them is a write.
- At least one of them is non-atomic.
- Neither one happens before the other.
Safe Rust makes this impossible through Send, Sync and the borrow rules. Data races become possible only when unsafe code bypasses those rules. Typical ways in are static mut, raw pointers sent across threads, and unsafe impl Sync on a type whose internals are not actually synchronized.
A data race is undefined behavior in Rust, as in C++. The program is invalid even if the racing value is "just a counter". Race-free atomic access is fine, and a race between two atomic operations is not a data race. Only a race involving a non-atomic access is.
How Miri finds races
Miri runs your program's threads on its own scheduler. It switches between threads at certain points, and the switching is deterministic for a given seed. It keeps a vector clock for each thread. A vector clock records, for every other thread, the latest operation this thread is known to have observed. For each memory location, Miri also records the clock of the last write and the last reads.
Synchronization operations create happens-before edges:
thread::spawnorders everything before the spawn ahead of everything in the new thread.joinorders everything in the finished thread ahead of everything after the join.- Releasing a
Mutexand then acquiring it orders the two critical sections. - An atomic store with
Release(or stronger) that is read by a load withAcquire(or stronger) orders what came before the store ahead of what comes after the load.
When a thread accesses a location, Miri compares the access against the recorded clocks. If it finds a conflicting access with no happens-before edge, it reports a race.
The key consequence is that Miri detects a missing ordering, not an unlucky overlap in time. The two accesses do not need to occur at the same instant. If your test ran them one after the other on a single CPU core, Miri still reports the race, because nothing in the program forced that order.
A first race
This is the program from the chapter's example, with a static mut counter incremented by two threads:
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. Natively, this program almost always finishes without complaint, because the two increments rarely collide. Miri reports something like this:
error: Undefined Behavior: Data race detected between (1) non-atomic write on thread `main` and (2) non-atomic write on thread `<unnamed>` at alloc1. (2) just happened hereThe report names three things:
- The kind of each access (here, two non-atomic writes).
- The two threads involved.
- The allocation, with a source location for the access that just happened.
Miri also points at the earlier conflicting access in a help note, so you can see both sides of the race. Reading those two locations, and asking what should have ordered them, is the whole diagnosis.
Not every program reports the same pair. The racing access that Miri sees second is the one it flags as "just happened", and that depends on the schedule.
Why `join` hides races
Moving the increment after the join removes the race:
use std::thread;
static mut COUNTER: u32 = 0;
fn main() {
let h = thread::spawn(|| unsafe {
COUNTER += 1;
});
h.join().unwrap();
unsafe {
COUNTER += 1;
}
println!("{}", unsafe { COUNTER });
}join creates a happens-before edge from the spawned thread's last operation to the main thread's next one. The two writes are ordered, so Miri accepts the program. Miri does not guess that the code is "morally fine". It checks ordering, and here the ordering is real.
Fixing the counter
For a shared counter, the usual fix is an atomic. An atomic access is never part of a data race, whatever the memory ordering:
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();
println!("{}", COUNTER.load(Ordering::Relaxed));
}This also drops static mut and unsafe entirely. Prefer that kind of fix when it is available. When you need to guard a larger structure, a Mutex is the simpler choice.
A subtler race: a flag with the wrong ordering
Atomics remove races on the atomic itself. They do not automatically protect other data. The next program publishes a plain u32 through an atomic ready flag, but uses Relaxed ordering:
use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
struct Shared {
data: UnsafeCell<u32>,
ready: AtomicBool,
}
unsafe impl Sync for Shared {}
fn main() {
let shared = Arc::new(Shared {
data: UnsafeCell::new(0),
ready: AtomicBool::new(false),
});
let producer = {
let shared = Arc::clone(&shared);
thread::spawn(move || {
unsafe { *shared.data.get() = 42 };
shared.ready.store(true, Ordering::Relaxed);
})
};
while !shared.ready.load(Ordering::Relaxed) {
std::hint::spin_loop();
}
let value = unsafe { *shared.data.get() };
println!("{value}");
producer.join().unwrap();
}The unsafe impl Sync is the programmer's promise that sharing Shared is safe. Miri does not trust that promise. It sees the producer's non-atomic write to data and the main thread's non-atomic read, with no happens-before edge between them, because a Relaxed store does not order earlier writes. Miri reports a race between a non-atomic write and a non-atomic read.
The fix is to use Release on the store and Acquire on the load. The pair creates the edge, so everything the producer wrote before the store is visible after the load:
shared.ready.store(true, Ordering::Release);
// ...
while !shared.ready.load(Ordering::Acquire) {
std::hint::spin_loop();
}Replace the two lines in the program above and Miri accepts it.
Schedules, seeds and many runs
Miri's default scheduler is deterministic for a given seed, and a seed changes which threads run when. Races that depend on ordering, such as the Relaxed flag example, are found on essentially any schedule, since the missing edge is always missing. Other bugs only appear on some schedules. Examples are a branch taken only when one thread wins, and a lock acquired in a different order.
Weak memory emulation adds another source of variation. Miri lets a relaxed or acquire load return an older value than the latest store, within the rules of the memory model. A bug can therefore appear only when a load happens to see a stale value.
These flags help explore schedules:
| Flag | Effect |
|---|---|
| `-Zmiri-seed=N` | Fixes the random seed so a failure can be reproduced exactly. |
| `-Zmiri-many-seeds=0..16` | Runs the program once per seed in the range and reports any seed that fails. |
| `-Zmiri-preemption-rate=R` | Sets how often Miri preempts a running thread. `0` means switch only when a thread blocks or yields. |
| `-Zmiri-disable-weak-memory-emulation` | Turns off the stale-load behavior. Use it only to narrow down a problem, not to hide one. |
| `-Zmiri-disable-data-race-detector` | Turns off race detection. Treat it as a last resort. |
A typical session looks like this:
MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri test
MIRIFLAGS="-Zmiri-seed=17" cargo +nightly miri testThe first command searches. When it names a failing seed, the second reproduces that run so you can debug it. Record the seed in the bug report.
Common mistakes
- Treating Miri's silence as proof. Miri only checks the executed schedule and the executed accesses. A race on a path your test never runs stays hidden.
- Writing tests with a single thread. If the test never spawns a second thread, no race can be found.
- Using
Relaxedeverywhere.Relaxedmakes the atomic itself race-free but publishes nothing else. UseReleaseandAcquire, or a lock, whenever other data depends on the atomic. - Disabling the detector to make a test pass. The report is almost never a false positive. Find the missing happens-before edge instead.
- Forgetting that races can hide in libraries. If a dependency uses unsafe code, Miri checks it too, because it interprets everything it executes. A race inside a dependency may need an upstream fix.
- Sleeping to order threads.
thread::sleepdoes not create happens-before edges. Miri still reports the race, and correctly so.
Summary of the workflow
- Run the multithreaded test under
cargo miri test. - Read both access locations in the report and the two thread names.
- Ask which synchronization should connect them: a lock, a join, or a Release and Acquire pair.
- Add that edge, or replace the shared plain access with an atomic or a
Mutex. - Re-run with
-Zmiri-many-seedsto check that no schedule still fails.
Exercise
A producer thread writes a plain u32 through an UnsafeCell and then does flag.store(true, Ordering::Relaxed). The consumer spins on flag.load(Ordering::Acquire) and then reads the u32. Miri reports a data race. Why, and what is the smallest change that fixes it?
Show answer
An Acquire load only creates a happens-before edge when it reads a value written by a Release (or stronger) store. The Relaxed store publishes nothing, so there is no edge from the producer's write of the u32 to the consumer's read, and the two non-atomic accesses race. Change the store to Ordering::Release. The Release store and Acquire load then pair up and order the write before the read.
Exercise
A test spawns two threads that each increment a static mut counter, but under cargo miri test it passes on seed 0 and fails on other seeds with a different "just happened" access. Is Miri giving a false positive on seed 0, and how would you reproduce one failing run?
Show answer
No. The increments have no happens-before edge on any schedule, so the program is racy on every seed. The seeds only change which of the two accesses Miri observes second, and so which one it labels as just happened. If seed 0 passed, the test did not reach both increments in a way Miri flagged, which is a reason to distrust a single run. To reproduce a failure, run with MIRIFLAGS="-Zmiri-seed=N" using a seed that failed, or search first with -Zmiri-many-seeds=0..32. Then fix the counter with AtomicU32 or a Mutex.