Sub topic 2
Why sharing mutable data between threads is a problem
This chapter assumes you know Rust ownership, borrowing and lifetimes, closures and move, and the basics of thread::spawn and JoinHandle. It also assumes you are comfortable with Result, unwrap and pattern matching. It introduces no new synchronization types. Its job is to show what goes wrong when threads share mutable data, so the tools in the next chapters make sense.
The problem in one sentence
A data race happens when two or more threads access the same memory at the same time, at least one of them writes, and nothing orders those accesses. In C and C++ a data race is undefined behavior. Safe Rust rules data races out at compile time. The cost is that the compiler refuses many programs that would be fine if you were careful. This chapter shows what it refuses, why, and what is still your responsibility.
An increment is not one step
Take the line counter += 1. It looks like a single operation, but the CPU performs three steps:
- Read the current value from memory into a register.
- Add one to the register.
- Write the register back to memory.
On a single thread these steps never interleave with anything else. With two threads they can interleave, and one update is lost.
This is a lost update. The result depends on timing, so it changes from run to run and often disappears under a debugger or with logging added. That is why this class of bug is hard to find after the fact.
What Rust does about it: aliasing XOR mutation
Rust's borrowing rules already encode the condition that makes races possible. At any moment a value has either of these:
- Any number of shared references (
&T), which can read but not modify the value. - Exactly one mutable reference (
&mut T), which can modify it and has no other access to it alive at the same time.
A data race needs aliasing (several threads can reach the value) together with mutation (at least one writes). The borrow checker never allows both through references at once. Threads reuse this rule, which is why you do not need a separate "thread checker" for the basic case.
First attempt: borrowing a local
Here is the most natural attempt at sharing a counter:
use std::thread;
fn main() {
let mut counter = 0;
let handle = thread::spawn(|| {
counter += 1;
});
handle.join().unwrap();
println!("{}", counter);
}This does not compile. The compiler reports error E0373: the closure may outlive the current function, but it borrows counter.
The reason is the signature of thread::spawn. Its closure must be 'static, meaning it cannot hold references to anything shorter-lived than the whole program. The compiler cannot see that join runs before main returns. A spawned thread could keep running after main has returned and counter has been freed. A borrowed counter would then be a dangling reference.
Second attempt: move silently copies
The compiler suggests adding move. For some types that compiles and does the wrong thing:
use std::thread;
fn main() {
let mut counter = 0;
let handle = thread::spawn(move || {
counter += 1;
counter
});
let inside = handle.join().unwrap();
println!("thread saw {inside}, main sees {counter}");
}This prints thread saw 1, main sees 0. An i32 implements Copy, so move gives the thread its own copy. The thread increments that copy and the original is untouched. The program is memory-safe but does not do what you wanted.
For a type that is not Copy, such as a Vec, move transfers ownership into the thread. Then the main thread can no longer use it. Neither outcome gives two threads one shared, modifiable value. That needs a different ownership model, and the next chapters build it.
A race the compiler cannot see
Safe Rust prevents data races, but it does not prevent every timing bug. The following program uses atomic integers, which Rust treats as safe to share. Each individual load and store is well-defined. The program splits the increment into two separate operations, which recreates the lost update from the diagram:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
static COUNTER: AtomicUsize = AtomicUsize::new(0);
fn main() {
let handles: Vec<_> = (0..4)
.map(|_| {
thread::spawn(|| {
for _ in 0..1000 {
let current = COUNTER.load(Ordering::Relaxed);
COUNTER.store(current + 1, Ordering::Relaxed);
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("{}", COUNTER.load(Ordering::Relaxed));
}The expected total is 4000. On a multi-core machine the program usually prints a smaller number, and the number changes between runs. A static has a 'static lifetime, so threads can reference it without move. Atomics also allow modification through a shared reference, which let mut integers do not.
There is no undefined behavior here. The program has a race condition, a logic error caused by timing, but not a data race. The compiler checks memory safety, not whether your sequence of operations is correct as a whole. The same distinction applies to every tool in this tutorial.
What a fix has to provide
A correct way to share a mutable value across threads needs two properties:
- Shared ownership. Several threads must each be able to keep the value alive, because none of them knows which will finish last. A single owner plus borrowed references cannot express that.
- Controlled mutation. Only one thread may modify the value at a time, and the read-modify-write must happen as one indivisible unit.
The standard library supplies one tool for each property:
| Need | Tool | Covered in |
|---|---|---|
| Several owners across threads | `Arc<T>` | Arc chapter |
| Only one thread at a time | `Mutex<T>` | Mutex chapter |
| Compiler check that a type is safe to share | `Send` and `Sync` | Send and Sync chapter |
| Indivisible operations on one integer or flag | Atomic types | Atomics chapter |
The two properties combine in Arc<Mutex<T>>, which is the main subject of this tutorial.
Why the compiler is strict
You may wonder whether this strictness is needed in real programs. A few facts explain why it is:
- Races are timing-dependent. A test can pass a thousand times and fail in production under different load or on different hardware.
- Compilers and CPUs reorder memory operations. Without synchronization, one thread may observe another thread's writes in a different order than the source code suggests.
- Torn or stale values are possible for larger types. A
StringorVecmodified from two threads can have its length, capacity and pointer updated at different moments, which corrupts the heap.
Because Rust checks this at compile time, the error messages you see in this tutorial are the cost of removing a whole category of runtime bug.
Summary of the failure modes
| Attempt | What happens | Why |
|---|---|---|
| Borrow a local in `thread::spawn` | Compile error E0373 | The closure must be `'static`, and the borrow could dangle |
| `move` a `Copy` value | Compiles, but each thread has its own copy | The original is never changed |
| `move` a non-`Copy` value | Compiles, but the main thread loses access | Ownership transfers to one thread |
| Split read and write on an atomic | Compiles, results vary | Race condition: the pair is not indivisible |
Exercise
A student writes let mut total = 0; and spawns four threads whose closures are move || { for _ in 0..100 { total += 1; } }. The program compiles and runs without error, and the main thread then prints total. What does it print, and why is this not a data race?
Show answer
It prints 0. total is an i32, which is Copy, so each move closure gets its own copy and increments only that copy. No memory is shared between threads, so there is no data race. The program is memory-safe but wrong, because the main thread's total is never changed. Sharing one value with controlled mutation needs Arc and Mutex, which the next chapters introduce.
Exercise
Why can the atomic program in this chapter print less than 4000 even though every load and store is individually safe?
Show answer
The increment is split into a separate load and a separate store. Two threads can load the same value, each add one, and each store the same result, so one increment is lost. The atomics make each single operation well-defined, but the load-then-store sequence is not indivisible. This is a race condition, not a data race. A single fetch_add performs the whole read-modify-write as one atomic step and avoids the lost update.