Sub topic 8
Mutable statics and why they are risky
This chapter assumes you know the basics of static items, threads (std::thread::spawn), and the five unsafe operations from earlier in this tutorial. Here you will see what a static mut is, why every access needs unsafe, how the compiler now restricts references to it, and which safe types usually replace it.
What a static is
A static item is a value with a fixed address that lives for the whole program, so it has the 'static lifetime. It is different from a const, which the compiler copies into each place it is used.
A plain static is immutable. Rust also requires its type to implement Sync, because any thread can read it at any time. A type that is not safe to share between threads, such as Cell<u32>, cannot be placed in a plain static.
What `static mut` adds
Adding mut makes the static writable from anywhere. The Sync requirement does not apply to a static mut. The compiler does not check whether two threads could touch it at once. Every read and write is therefore an unsafe operation:
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}");
}The code prints 3. The SAFETY comment names the condition that makes the access sound: only one thread exists. If someone later adds a second thread that calls add_to_count, that comment becomes false and nothing in the compiler warns you.
Why it is risky
A static mut has two kinds of risk.
Data races
A data race happens when two threads access the same memory at the same time, at least one access is a write, and there is no synchronization between them. In Rust a data race is undefined behavior. Even COUNTER += 1 is not one indivisible step. It reads the value, adds one, and writes the result back. Two threads can read the same old value and both write the same new value, so one increment is lost. That is the mild outcome. Because the access is undefined behavior, the compiler is also allowed to assume it never happens and optimize on that assumption.
Aliasing
The second risk affects even single-threaded code. Rust requires that a &mut T is the only live path to its value while the reference exists. A global is reachable from every function in the program, so it is easy to create two paths to it without noticing:
- A function takes
&mut COUNTERand calls another function. - That second function also reads or writes
COUNTERdirectly. - Now the first
&mutis no longer unique, and the program has undefined behavior.
The compiler cannot see this because the access happens through the global name, not through a function parameter.
References to a `static mut`
Because of the aliasing problem, creating a reference to a static mut is discouraged. The static_mut_refs lint flags both &COUNTER and &mut COUNTER. It warns in editions before 2024 and is an error by default in the 2024 edition.
Implicit references count too. A call like println!("{}", COUNTER) takes a shared reference to COUNTER behind the scenes. That is why the example above copies the value into a local variable first.
If you must work with a static mut without making a reference, take a raw pointer. The &raw const and &raw mut operators create a raw pointer directly, without creating a reference in between. They are stable since Rust 1.82, and taking the address is safe. Only dereferencing the pointer needs unsafe:
static mut COUNTER: u32 = 0;
fn main() {
let p = &raw mut COUNTER;
// SAFETY: the program is single-threaded and `p` points to the
// static, which is valid, aligned, and initialized for the whole run.
unsafe {
*p += 1;
let v = *p;
println!("{v}");
}
}This prints 1. The pointer approach removes the reference rule from your worries. It does not remove the data race rule. You still need to guarantee that no other thread touches the static at the same time.
Safe replacements
In almost every case a safe type does the same job. These types are designed to be placed in a plain static, which is why they work from many threads.
| Need | Use | Notes |
|---|---|---|
| A shared counter or flag | `AtomicU32`, `AtomicBool`, and so on | No lock needed. You choose a memory `Ordering`. |
| Shared data with changing contents | `Mutex<T>` or `RwLock<T>` | `Mutex::new` is a `const fn`, so it can initialize a static. |
| A value computed once, then read many times | `OnceLock<T>` | Initialization happens at most once, even with racing threads. |
| A value per thread | `thread_local!` | Each thread gets its own copy, so there is no sharing at all. |
Atomics
An atomic integer lets many threads update one number safely:
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn main() {
let handles: Vec<_> = (0..4)
.map(|_| {
thread::spawn(|| {
for _ in 0..1000 {
COUNTER.fetch_add(1, Ordering::Relaxed);
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("{}", COUNTER.load(Ordering::Relaxed));
}The program always prints 4000. The static is not mut, and there is no unsafe anywhere. Ordering::Relaxed is enough here because only the count matters and no other data depends on it.
Mutex
When the shared value is more than a number, put it behind a Mutex:
use std::sync::Mutex;
static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn record(message: &str) {
LOG.lock().unwrap().push(message.to_string());
}
fn main() {
record("start");
record("finish");
println!("{} entries", LOG.lock().unwrap().len());
}This prints 2 entries. The lock guard is dropped at the end of each statement, so the lock is held only briefly.
OnceLock
For a value that is set up once, such as configuration, OnceLock replaces the common pattern of writing a static mut during startup and reading it afterward:
use std::sync::OnceLock;
static CONFIG: OnceLock<String> = OnceLock::new();
fn config() -> &'static str {
CONFIG.get_or_init(|| String::from("default"))
}
fn main() {
println!("{}", config());
println!("{}", config());
}The closure runs on the first call only. After that every caller gets the same shared reference.
Choosing an approach
The diagram shows the order in which to ask the questions.
Two situations still lead people to static mut:
- Embedded or bare-metal code. There may be no operating system, no threads, and no allocator. Even there, the usual advice is to wrap the data in a type that confines access, such as a critical-section mutex.
- Interfacing with C. A C library may export a global variable. You declare it in an
unsafe externblock, and access to it is unsafe for the same reasons.
Rules if you must use `static mut`
- Never create a reference to it. Use
&raw constand&raw mut, or copy values in and out. - Write a
SAFETYcomment at every access that states why no other thread can access the static at that time. - Keep the static private to one module, and expose only a small safe function that holds the unsafe code. This is the safe abstraction pattern from earlier in the tutorial.
- Do not call code you do not control while holding a pointer to the static. That code could reach the same global.
- Remember that a
static mutis never dropped. Its destructor does not run at program exit.
Summary
- A
staticlives for the whole program. A plainstaticmust beSync. Astatic muthas no such check, so every access is unsafe. - The risks are data races between threads and aliased
&mutreferences. - Do not take references to a
static mut. Use raw pointers made with&raw mut, or copy values. - Atomics,
Mutex,OnceLock, andthread_local!cover nearly every case withoutunsafe.
Exercise
A teammate writes unsafe { println!("{}", COUNTER); } where COUNTER is a static mut u32, and the 2024 edition rejects it. What is the cause, and how would you fix the code so it still reads the value without changing COUNTER to a different type?
Show answer
The println! macro takes a shared reference to its argument, so the code creates a &u32 pointing at the static. The static_mut_refs lint is deny-by-default in the 2024 edition because such a reference can alias a write from elsewhere. Copy the value first: let v = unsafe { COUNTER }; println!("{v}");. The read is still unsafe, but no reference to the static exists. Replacing COUNTER with an AtomicU32 would be better if more than one thread could use it.
Exercise
Why is it correct to declare static COUNTER: AtomicU32 = AtomicU32::new(0); without mut, even though the program changes the counter?
Show answer
AtomicU32 uses interior mutability: its methods take &self and perform the update with atomic hardware instructions. It implements Sync, so it is allowed in a plain static. The compiler can then guarantee that concurrent updates are not data races.