Contents
Mutex and Condvar are higher-level ways to share data between threads in Rust. Lower down the stack you have atomics — hardware-backed operations on individual locations.
Below: Atomic* types and Ordering, mostly through runnable examples.
Why bother with atomics if Mutex already exists? Compare the two.
Mutex vs Atomic
1. How they touch data
Mutex enforces exclusive access: many threads may try to write, but only one holds the lock at a time. Everyone else waits until it is released.
Atomic operations are indivisible at the machine level — built on CPU primitives like load, store, compare-and-swap (CAS), and fetch-add. Each operation completes fully or not at all; there is no halfway state where another thread can tear the update apart.
So atomics lean on non-splittable instructions for lock-free access to a single memory location.
2. Critical sections
With Mutex, the protected region sits between lock() and unlock().
An atomic only guarantees atomicity for that one address. If your critical section involves more state, you typically combine load/store/CAS with a spin loop — the lower-level cousin of a mutex. That shows up when you care about every nanosecond.
Pseudo-code for a flag-based critical section (the Ordering section below makes this concrete):
1 | thread 1: |
First look at Atomic
A minimal two-thread example:
1 | use std::{ |
Two threads store and load FLAG. The reader prints when it sees true.
You might run this and not see the print. Scheduling could run load before store, and that alone would explain a miss — but that is not the whole story.
The rest involves instruction reordering and atomic Ordering.
Instruction reordering
1 | fn f(a: &mut i32, b: &mut i32) { |
You write one sequence; the CPU or compiler may execute an equivalent faster one:
1 | fn f(a: &mut i32, b: &mut i32) { |
Why?
As long as single-thread semantics stay the same, instructions may be reordered for speed — execution order is not guaranteed to match source order.
On one thread that is often fine. Across threads, even two atomics in the same thread can be reordered relative to each other, so “I used atomics” does not automatically mean “I fixed the order other threads observe.”
Example — steps 1 and 2 in thread b are independent, so they may swap:
1 | use std::{ |
Ordering constrains when an atomic’s effect becomes visible to other threads, so concurrent updates are more predictable.
Ordering
Rust’s Ordering aligns with C++20 memory order for the most part. The variants:
- Relaxed
The weakest guarantee: the operation itself is atomic, but there is no ordering promise for how this store/load relates to other memory accesses on other threads (as in the reordering example).
- Acquire
For loads. No other reads or writes on this thread may be reordered before this load. Release stores to the same location from other threads that happened before you see the loaded value are visible.
- Release
For stores. No other reads or writes on this thread may be reordered after this store. Threads that later do an Acquire load on the same location will see this write.
So pairing Release (writer) with Acquire (reader) is the usual handoff: “data is ready” on the flag, payload writes before the Release, reads after the Acquire.
See comments in the code for where reordering is forbidden:
1 | use std::{ |
- AcqRel
For read-modify-write ops: Acquire semantics on the read side, Release on the write side.
- SeqCst
Acquire/Release plus a single total order of all SeqCst atomics that every thread agrees on. Interleavings can still vary run to run, but once a particular execution has happened, there is no alternate consistent ordering of those SeqCst operations — as if they ran on one global timeline.
Strictness ramp: Relaxed → Acquire/Release → SeqCst, with cost usually going up as well.
Building a critical section with explicit orderings:
1 | use std::sync::atomic::{AtomicBool, Ordering}; |
Seeing the difference in visibility
Does the ordering strength matter in practice? Try Relaxed first:
1 | use std::{ |
S often ends up above 100000. Why?
Both AtomicBools start false. Each thread stores its flag true with Relaxed, then loads the other. If the load still sees false, it increments S.
Possibilities:
Other thread’s instructions reordered
- Store happens after the load; increment (under Relaxed).
No reordering
- Other thread has not stored yet → increment.
- Other thread stored but load does not see it yet → increment (Relaxed).
- Load sees the store → no increment.
Reordering plus weak visibility both push S up. Run 100000 iterations and overshooting 100000 is easy with Relaxed.
Switch the bool ops to SeqCst: no reordering like above, and a global order on those atomics. If the other thread’s store is before your load in that order, you see it — you do not get both threads thinking the partner is still false. S tops out at 100000.
1 | let t1 = thread::spawn(move || { |
fence
Ordering applies per atomic op. fence adds a memory barrier across multiple atomics (and surrounding accesses), blocking certain reorders — another way to stitch a critical section together.
1 | a.store(1, Release); |
1 | a.load(Acquire); |
Fences help when several locations need a coordinated visibility story. You can mix Relaxed ops with a fence instead of tagging every operation AcqRel/SeqCst.
Toy mutex built from CAS + fences:
1 | use std::sync::atomic::AtomicBool; |
Lazy initialization
Atomics often back lazy init of shared static-like data:
1 | use std::{ |
In real code you rarely hand-roll this — crates like once_cell cover the pattern.
Atomics are the low-level layer. Ordering ties atomic results to what other threads can observe and pushes back on compiler/CPU reordering. You might never ship your own lock-free structure, but knowing this makes library code and the ordering names far easier to read.
Solid follow-ups:
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
