In Rust, one thread boxes a `Config` and stores its pointer in a static `AtomicPtr<Config>` for reader threads; which orderings make that safe, and what goes wrong with `Relaxed`?
answer
- the pointer is atomic, the pointee is not
- pair the store with the load
- happens-before through a synchronizes-with edge
- Miri reports a data race
basics
~20 sStore the pointer with Ordering::Release and load it with Ordering::Acquire, so a reader that sees the pointer also sees the writes that built the Config. With Relaxed, reading those fields is a data race, which is undefined behaviour.
solid answer
~50 sThe pointer itself is atomic; the `Config` fields behind it are ordinary memory written before the store. A `Release` store on the `AtomicPtr` paired with an `Acquire` load that reads that pointer creates a synchronizes-with edge, so every write the builder made before the store happens-before everything the reader does after the load — dereferencing is then sound. With `Relaxed` on either side and no fence, there is no such edge: the reader can see the non-null pointer while the field writes are unordered with its reads, and the `unsafe { &*p }` is a data race, which is undefined behaviour. Miri reports exactly that. It may pass every test on x86-64 and still be wrong. `SeqCst` on both sides also works but is not needed. A `Relaxed` load followed by `fence(Ordering::Acquire)` is an equivalent reader. In safe code, `OnceLock<Config>` does this publishing for you.
code
rust · 32 linesuse std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::thread;
struct Config {
max_conns: u32,
name: String,
}
static CONFIG: AtomicPtr<Config> = AtomicPtr::new(ptr::null_mut());
fn main() {
let loader = thread::spawn(|| {
let cfg = Box::new(Config { max_conns: 64, name: String::from("edge") });
// Release: every write that built `cfg` happens-before an Acquire load that sees this pointer
CONFIG.store(Box::into_raw(cfg), Ordering::Release);
});
let reader = thread::spawn(|| loop {
let p = CONFIG.load(Ordering::Acquire);
if !p.is_null() {
// SAFETY: p came from Box::into_raw and is never freed while readers run
let cfg = unsafe { &*p };
return (cfg.max_conns, cfg.name.clone());
}
std::hint::spin_loop();
});
loader.join().unwrap();
println!("{:?}", reader.join().unwrap());
// reclaim at shutdown
let p = CONFIG.swap(ptr::null_mut(), Ordering::Acquire);
drop(unsafe { Box::from_raw(p) });
}go deeper
Recall the rule of thumb: the thread that publishes stores with Release, and the thread that reads the published data loads with Acquire.
Explain that the pointer is atomic but the fields behind it are not, and that only a Release store read by an Acquire load orders those field writes before the reads.
Diagnose a Relaxed publish as undefined behaviour, reproduce it with Miri, explain why x86-64 hides it, and know the Acquire fence and AcqRel swap variants.
Ask whether hand-rolled AtomicPtr publishing is justified at all when OnceLock covers write-once data, and who owns the reclamation story if the value is ever swapped.
## What is being published The scenario: a loader thread builds a `Config` on the heap, turns the `Box` into a raw pointer with `Box::into_raw`, and stores it in `static CONFIG: AtomicPtr<Config>`. Reader threads spin until the pointer is non-null, then dereference it. Two kinds of memory are involved: - the **pointer**, which lives in the atomic and is read and written with atomic operations; - the **pointee** — `max_conns`, the `String`'s heap buffer — written with ordinary, non-atomic stores while the box was built. The question is not whether the reader sees the pointer (it eventually will, with any ordering) but whether it is guaranteed to see the fields that pointer leads to. ## Release and Acquire as a pair The library documents `Release` as: when coupled with a store, "all previous writes become visible to all threads that perform an `Acquire` (or stronger) load of this value". `Acquire` is the matching half: if a load with `Acquire` reads a value written by a `Release` store, all subsequent operations of the reader are ordered after that store. 1. The loader writes the `Config` fields (ordinary writes). 2. The loader does `CONFIG.store(ptr, Ordering::Release)`. 3. A reader does `CONFIG.load(Ordering::Acquire)` and gets `ptr`. 4. The reader dereferences `ptr`. Because step 3 read the value written in step 2, the store **synchronizes with** the load, and step 1 **happens-before** step 4. The non-atomic reads in step 4 are ordered after the non-atomic writes in step 1, so they do not race. The pairing is per location: an `Acquire` load of some other atomic gives no guarantee about this one. ## What `Relaxed` breaks Make either side `Relaxed`, with no fence to compensate, and the synchronizes-with edge disappears. The reader can observe the new pointer, yet its reads of the fields are unordered with the loader's writes. The memory model in `core::sync::atomic` defines a **data race** as conflicting accesses, at least one non-atomic, where neither happens-before the other — and data races are **undefined behaviour**. That is what the `Relaxed` version contains. Running the `Relaxed` variant under Miri (`cargo +nightly miri run`) stops with "Undefined Behavior: Data race detected" at the `unsafe { &*p }` line, pointing back at the `store`. The `Release`/`Acquire` version runs clean under Miri. Why does the broken version usually "work"? The Rustonomicon notes that on strongly ordered platforms such as x86-64 most accesses already have release or acquire semantics, making them often free. But the compiler may still reorder the field writes past a `Relaxed` store, and weakly ordered CPUs such as AArch64 reorder in hardware. Passing tests on one machine proves nothing. ## The orderings at a glance | Store / load | Reader may dereference? | Notes | |---|---|---| | `Release` / `Acquire` | yes | the minimal correct pair | | `SeqCst` / `SeqCst` | yes | also correct; adds one global order over all SeqCst operations | | `Release` / `Relaxed` then `fence(Acquire)` | yes | the fence upgrades the reader once it has seen the pointer | | `Relaxed` / `Acquire` | no | the store releases nothing | | `Release` / `Relaxed`, no fence | no | the load acquires nothing | An operation that both reads and writes — `swap`, `compare_exchange`, `fetch_add` — takes `AcqRel` when it must do both jobs, for example a `swap` that installs a new config and hands back the old pointer. `SeqCst` matters only when correctness depends on one global order across several atomics; plain publishing never needs it. ## Why this needs `unsafe` at all Safe Rust cannot express the bug. Dereferencing a raw pointer requires an `unsafe` block, and the `SAFETY` comment there is where the ordering argument lives: "the pointer was stored with `Release`, I loaded it with `Acquire`, the pointee is never freed while readers run". A wrong ordering in purely safe atomic code is a logic error; a wrong ordering that guards unsafe access is undefined behaviour. Two further points the snippet glosses over: - **Freeing.** The snippet frees the box only at shutdown, after every reader has finished. Replacing and freeing a published config while readers may still hold the old pointer is the reclamation problem of lock-free structures, which orderings alone do not solve. - **The safe alternative.** If the config is written once, `std::sync::OnceLock<Config>` performs the same release-and-acquire publishing internally, with no `unsafe` in your code. Hand-rolled `AtomicPtr` publishing earns its place only when the value must later be swapped.
- The reader loop calls `load` thousands of times before the pointer appears. Can it use a cheaper load and still be correct?Yes: load with `Ordering::Relaxed` in the loop and, once the pointer is non-null, call `std::sync::atomic::fence(Ordering::Acquire)` before dereferencing. An Acquire fence after a load that read a value written by a Release store establishes the same happens-before edge. Miri accepts this variant. On x86-64 the saving is nil; on weakly ordered CPUs it moves the barrier out of the loop.
- The loader later replaces the config with `CONFIG.swap(new_ptr, Ordering::AcqRel)`. Why `AcqRel`, and is freeing the returned old pointer now safe?`AcqRel` makes the swap release the new config's writes to later readers and acquire the previous publisher's writes for the old pointer it returns. Freeing that old pointer is still not safe if a reader may have loaded it and still be using it; that needs a reclamation scheme such as reference counting or epochs, which orderings cannot provide.
- Relaxed is fine because the pointer store itself is atomic.
- Acquire on the load alone is enough; the store can be Relaxed.
- Publishing data between two threads requires SeqCst on both sides.
- If it passes every test on x86-64, the orderings are correct.
- Safe Rust alone can produce this data race on the Config fields.