Data race
A data race is two threads accessing the same memory at once, at least one writing, without a synchronisation that orders them. In Rust that is undefined behaviour, and safe code is not supposed to be able to do it.
Detailed Explanation
C and C++ programs hit data races when two threads write x without a lock. The language says that is undefined behaviour. Rust says the same, then designs the type system so that safe code cannot form the race. Two &mut T cannot exist at once. A &T cannot coexist with a &mut T. Send and Sync stop you from moving a Rc or a RefCell to another thread. Mutex and atomics are the approved ways to share writes.
A data race is not the same as a race condition. A race condition is any timing-dependent bug: you locked correctly but in the wrong order, or you checked then acted. Those compile. They deadlock or corrupt application state. A data race is the memory-model crime: unsynchronised conflicting access. unsafe plus a raw pointer, a wrong unsafe impl Send, or FFI can still create one. Safe Rust plus the standard locks should not.
The compiler's rejection is the feature. thread::spawn with a captured &mut count does not compile. The fix is not unsafe. The fix is Arc<Mutex<u32>>, an atomic, or a channel that owns the counter on one thread.
Tools: the type system first. Then cargo +nightly miri for some unsafe races. ThreadSanitizer for C FFI. There is no TSAN-on-safe-Rust story you should need if you stayed safe.
When you think about data races: every unsafe impl Send/Sync, every raw pointer shared with a thread, every C library that stores a pointer you passed. When you have a race condition: look at lock order, at TOCTOU, at message order — not at unsafe first.
Code Examples
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let n = Arc::new(AtomicU32::new(0));
let n2 = Arc::clone(&n);
let h = thread::spawn(move || {
n2.fetch_add(1, Ordering::Relaxed);
});
n.fetch_add(1, Ordering::Relaxed);
h.join().unwrap();
println!("{}", n.load(Ordering::Relaxed)); // prints: 2
}Common Gotchas
A data race is UB, not a torn integer you can ignore
The optimiser may delete later reads. Do not "just use a usize" across threads.
Safe Rust without `unsafe` should not data-race
If it does, that is a compiler or std bug. Application bugs are usually race conditions with locks.
`unsafe impl Sync` is how people invent races
A raw pointer to unsynchronised memory is the typical mistake.
FFI can race even when Rust looks safe
If C stores the pointer and another thread writes, you have a race the borrow checker cannot see.