skip to content

In Rust, why can a `static REQUESTS: AtomicUsize` be incremented from many threads without `static mut`, `unsafe` or a `Mutex`?

level: juniorimportance: should knowfreq 45%

answer

  1. which receiver the method takes
  2. interior mutability inside the type
  3. Sync plus a const constructor
  4. fetch_add returns the old value

basics

~20 s

Atomic methods such as fetch_add take &self, not &mut self, so an immutable static can be updated through them; AtomicUsize is Sync, and AtomicUsize::new is a const fn, so it can initialise a static directly.

solid answer

~40 s

A plain `static COUNT: usize` cannot be assigned (E0594), and a `static mut` needs `unsafe` for every access (E0133). An `AtomicUsize` avoids both because every operation — `load`, `store`, `fetch_add`, `swap`, `compare_exchange` — takes `&self`: the type wraps its integer in an `UnsafeCell` and changes it with an atomic instruction, so mutation through a shared reference is sound. The type implements `Sync`, which a `static` requires, and `AtomicUsize::new` is a `const fn`, so `static REQUESTS: AtomicUsize = AtomicUsize::new(0);` compiles. `REQUESTS.fetch_add(1, Ordering::Relaxed)` returns the value before the add and wraps on overflow instead of panicking. No `Arc` is needed for a static; a local atomic is shared through `Arc` or a scoped thread.

code

rust · 20 lines
rust
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

// No `mut`, no `unsafe`: every atomic method takes &self.
static REQUESTS: AtomicUsize = AtomicUsize::new(0);

fn handle_request() -> usize {
    // fetch_add returns the value *before* the add
    REQUESTS.fetch_add(1, Ordering::Relaxed) + 1
}

fn main() {
    let workers: Vec<_> = (0..4)
        .map(|_| thread::spawn(|| for _ in 0..1000 { handle_request(); }))
        .collect();
    for w in workers {
        w.join().unwrap();
    }
    println!("total = {}", REQUESTS.load(Ordering::Relaxed)); // total = 4000
}

go deeper

for a junior

Recall that atomic methods take &self, that the static needs no mut and no unsafe, and that fetch_add hands back the old value.

for a middle

Explain the UnsafeCell inside the atomic, why a static must be Sync, why new being const matters, and that fetch_add wraps on overflow.

for a senior

Point out when one atomic is not enough, such as two counters that must stay consistent, and how get_mut and into_inner avoid atomic instructions once access is exclusive.

for a principal

Frame process-wide atomic statics as global state: fine for metrics, but argue for passing explicit handles when tests or multiple instances need isolated counters.

## The two ways a plain static fails A `static` item is one value with a fixed address for the whole run of the program, and every thread can name it. That is exactly why Rust is strict about changing it: - `static COUNT: usize = 0;` followed by `COUNT += 1;` is rejected with **E0594**, "cannot assign to immutable static item". A non-`mut` static is immutable. - `static mut HITS: usize = 0;` followed by `HITS += 1;` is rejected with **E0133**, "use of mutable static is unsafe and requires unsafe block". Two threads incrementing a `static mut` at once is a **data race**, which is undefined behaviour, so the compiler makes you write `unsafe` and take the responsibility yourself. Neither is what you want for a request counter that every handler thread bumps. ## Why an atomic static compiles `std::sync::atomic::AtomicUsize` changes the shape of the problem rather than hiding it: 1. **Every operation takes `&self`.** `load`, `store`, `swap`, `fetch_add`, `fetch_sub`, `compare_exchange` and the other atomic operations all borrow the atomic immutably. A shared reference to a static is always available, so there is nothing to assign to and E0594 never arises. 2. **The value lives in an `UnsafeCell`.** In the 1.99 standard library `AtomicUsize` is an alias for a generic `Atomic<usize>` whose single field is an `UnsafeCell`. `UnsafeCell` is the one sanctioned way to mutate through `&`, and the methods do that mutation with atomic machine instructions, so two threads touching the value at once is not a data race. 3. **It is `Sync`.** A `static` must be `Sync` because any thread can reach it; the atomic types carry `unsafe impl Sync` in core, so the compiler accepts them. 4. **`new` is a `const fn`.** A static's initialiser must be evaluated at compile time, and `AtomicUsize::new(0)` qualifies. No lazy initialisation is involved. ```rust use std::sync::atomic::{AtomicUsize, Ordering}; static REQUESTS: AtomicUsize = AtomicUsize::new(0); fn on_request() { REQUESTS.fetch_add(1, Ordering::Relaxed); } ``` ## What `fetch_add` returns The `fetch_` prefix means "fetch the old value, then apply the operation". `REQUESTS.fetch_add(1, Ordering::Relaxed)` returns the value **before** the addition, so a handler that wants its own request number writes `fetch_add(1, …) + 1`. The library documents that the operation **wraps around on overflow**: unlike the `+` operator in a debug build, it never panics. On a 64-bit target a `usize` counter will not wrap in practice; on a 32-bit target a long-running counter can. Every call also names an `Ordering`. Rust has no default ordering for atomics. For a counter that nothing else depends on, `Ordering::Relaxed` is the usual choice: the increment is still a single indivisible step, so no increments are lost. ## Reading the value back | Operation | Receiver | Use it when | |---|---|---| | `load(order)` | `&self` | other threads may still be updating it | | `get_mut()` | `&mut self` | you own the atomic exclusively, so no atomic instruction is needed | | `into_inner()` | `self` | you are consuming the atomic and want the plain integer | A static can only be read with `load`, because nobody ever holds `&mut` to a static. ## Sharing an atomic that is not a static A static is the simplest sharing mechanism, but the atomic types themselves do not provide sharing. A local `AtomicUsize` is shared by putting it in an `Arc<AtomicUsize>` and cloning the `Arc` into each spawned thread, or by borrowing it from threads started with `thread::scope`. There is no reason to wrap it in a `Mutex`: the atomic already makes each operation safe. ## When an atomic is the wrong tool An atomic protects exactly one machine-sized value. Keep these limits in mind: - Two counters that must change together (requests and bytes, say) need a lock or a single combined value; two separate atomics can be observed half-updated. - Not every target supports every operation. The docs mark `fetch_add` and `compare_exchange` as available only on platforms with atomic read-modify-write for that size; some small microcontrollers provide only atomic load and store. - A `Mutex<usize>` that guards nothing but the number is the opposite mistake: it works, but every increment takes and releases a lock where one atomic instruction would do. - A counter is fine with `Relaxed`. A flag that announces "the data is ready" needs stronger orderings, which is a separate subject.

  • Why does a handler that writes `let id = REQUESTS.load(Relaxed) + 1; REQUESTS.store(id, Relaxed);` hand out duplicate ids?
    The `load` and the `store` are two separate atomic operations. Another thread can load the same value between them, and both store the same `id`, so one increment is lost and two requests share a number. `fetch_add` performs the read, the add and the write as one indivisible read-modify-write, so each caller receives a distinct previous value.
  • Your function owns a `Vec<AtomicUsize>` of per-shard counters after all worker threads have joined. How do you read them without atomic loads?
    Use `get_mut` on each element through `&mut`, or consume the vector and call `into_inner` on each atomic. Both are allowed because exclusive access proves no other thread can touch the values, so the compiler can use ordinary memory accesses.

  • A static can only be changed through static mut and an unsafe block.
  • fetch_add returns the new value after the addition.
  • fetch_add panics on overflow in debug builds, like the + operator.
  • An AtomicUsize must sit inside a Mutex before threads can share it.
  • A static atomic still needs an Arc to be used from spawned threads.