Sub topic 8
Mutable statics and why they are risky
This chapter assumes you know what unsafe blocks permit, how raw pointers work, and what undefined behavior (UB) means. It also assumes you can read basic std::thread code.
What a mutable static is
A static is a value with a fixed address that lives for the whole program. A normal static is immutable. Adding mut lets any code in the program change it:
static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
// SAFETY: this program is single-threaded, so there are no data races.
unsafe {
COUNTER += inc;
}
}
fn main() {
add_to_count(3);
// Copy the value out instead of taking a reference to the static.
let value = unsafe { COUNTER };
println!("{value}");
}Reading or writing a static mut is one of the five unsafe operations. The compiler requires unsafe here because it cannot prove that two threads will not touch COUNTER at the same moment.
Why it is risky
Ownership normally guarantees that mutable access is exclusive. A static mut is global, so the borrow checker has no owner to track. Two problems follow.
- Data races. If one thread writes while another reads or writes, the program has UB. This holds even for a plain integer.
- Aliasing violations. A
&mutreference promises exclusive access. If you create&mut COUNTERwhile another reference to it exists, you have broken that promise, even in one thread.
The first problem looks like this:
The diagram shows a lost update. In Rust a real data race is worse than a wrong number, because it is UB and the compiler may assume it never happens.
References to statics
Taking a reference to a static mut is the subtler trap. Code such as println!("{}", COUNTER) or COUNTER.push(1) creates a reference behind the scenes. The static_mut_refs lint warns about this, and in the 2024 edition it is denied by default.
You have two ways to stay out of trouble:
- Copy the value out, as
maindoes above. - Use a raw pointer, written
&raw mut COUNTER, and dereference it only insideunsafe.
static mut LOG_LEVEL: u8 = 1;
fn main() {
unsafe {
let p = &raw mut LOG_LEVEL;
*p = 3;
println!("{}", *p);
}
}This avoids creating a long-lived reference. It does not fix data races. You must still ensure that no other thread accesses the static at the same time.
Prefer a safe alternative
Most uses of static mut have a safe replacement that the compiler can check.
| Need | Safe choice |
|---|---|
| Shared counter or flag | `AtomicU32`, `AtomicBool` and similar |
| Shared structured data | `static Mutex<T>` |
| Value set once, then read | `OnceLock<T>` |
The counter from the start of the chapter becomes this:
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn add_to_count(inc: u32) {
COUNTER.fetch_add(inc, Ordering::Relaxed);
}
fn main() {
add_to_count(3);
println!("{}", COUNTER.load(Ordering::Relaxed));
}There is no mut and no unsafe, and it is correct from any number of threads.
When `static mut` is still used
Some code runs where Mutex and std are unavailable, such as embedded firmware before interrupts start. There, a static mut with a documented access protocol can be reasonable. Even then, wrap it in a small module with a safe API, so the unsafe access lives in one place.
Exercise
Why does static mut COUNTER need unsafe to read, even if the type is a plain u32? Name a safe replacement.
Show answer
The compiler cannot verify that no other thread writes it at the same time, and an unsynchronized read racing with a write is undefined behavior. AtomicU32 (or a Mutex<u32>) makes the access safe.