Atomics and Memory Models
2026-10-29
This module: Concurrent programming with threads
Recommended: Rust Atomics and Locks, Ch 1-3
Arc<T>: Atomically reference-counted allocated T objectMutex<T>: Lock-guarded T object
lock returns a LockResult<MutexGuard<T>>MutexGuard releases the lockRwLock<T>: Allows multiple readers or one writerCondvar: Used to signal a condition (e.g. queue empty)On Rc or Arc:
clone() increments the (strong) ref countdrop decrements the reference countAtomic updates avoid leaks or double-drops!
Common pattern: Arc<Mutex<T>>
Arc to share ownershipMutex for mutual exclusionAnalogous to Rc<RefCell<T>> in serial code
When is a Rust Mutex unlocked?
unlock methodMutexGuard is droppedRespond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333
Data races (undefined behavior) happen when
Atomic operations act indivisibly
Rust pretty blatantly just inherits the memory model for atomics from C++20. This is not due to this model being particularly excellent or easy to understand. Indeed, this model is quite complex and known to have several flaws. Rather, it is a pragmatic concession to the fact that everyone is pretty bad at modeling atomics.
– Rustonomicon
“It’s the difference between riding a rollercoaster and building one mid-air while it’s on fire – and you’re also the passenger.”
– Julian Goldstein, yeet blog
Also: “It’s fast, it’s elegant, and it will absolutely kill you if you do it wrong.”
“Atomics!”
– Gurney Halleck (played by Patrick Steward), Dune, 1984
(The characters all put on some type of helmet, drop a nuke… and then take their helmets off to go riding through the fallout. On the backs of giant carnivorous worms. That’s safe?)
Performance!
AtomicBool, AtomicUsize, etc)Ordering argument (more on this later)
Relaxed is the least restrictive(Examples adapted from Rust Atomics and Locks, Ch 2)
use std::sync::atomic::{self, AtomicBool, Ordering::Relaxed};
use std::thread;
fn main() {
let stop = AtomicBool::new(false);
thread::scope(|s| {
s.spawn(|| { while !stop.load(Relaxed) { bg_work(); } });
for line in std::io::stdin().lines() {
match line.unwrap().as_str() {
"stop" => break,
cmd => println!("unknown command: {cmd:?}"),
}
}
stop.store(true, Relaxed);
});
}(Probably better: std::sync::LazyLock)
impl AtomicI32 {
pub fn fetch_add(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_sub(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_or(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_and(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_nand(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_xor(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_max(&self, v: i32, ordering: Ordering) -> i32;
pub fn fetch_min(&self, v: i32, ordering: Ordering) -> i32;
pub fn swap(&self, v: i32, ordering: Ordering) -> i32; // "fetch_store"
}What about overflow?
What could go wrong here?
Probably mostly OK.
Much more flexible:
If value is expected, change to new and return Ok(expected); otherwise return Err(value).
Possible issue in some cases:
load a value Acompare_exchange succeeds even with changeA “natural” mental model: Execution is consistent with a sequential interleaving of thread instructions.
Sequential consistency is expensive! Cheaper options?
Agreed-upon orderings described by happens-before:
f(); g(); gives f() happens-before g()Assume:
But no other happens-before relations
Which output is impossible?
Respond at: https://PollEv.com/davidbindel252 or send davidbindel252 to 22333
Add happens-before between matched loads/stores
ReleaseAcquireAcqRelfn main() {
let spinlock = Arc::new(AtomicUsize::new(1));
let spinlock_clone = Arc::clone(&spinlock);
let thread = thread::spawn(move || {
spinlock_clone.store(0, Ordering::Release);
});
// Wait for other thread to release lock
while spinlock.load(Ordering::Acquire) != 0 {
hint::spin_loop();
}
thread.join().unwrap();
}Acquire, Release, AcqRel, or SeqCstShared memory requires synchronization!
On Ed: What do you think would be good final questions for this class?
Also: Happy Halloween weekend!