Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
Migration, interop & safety guarantees: how to port C++ code to Rust — sum types instead of inheritance, ownership transfer, cxx/bindgen, incremental Ship-of-Theseus migration and verifying what you translated.
Module 12 gave you the standard answer to shared data: Mutex + Arc.
This deep-dive module drills one layer lower. The atomic types in
std::sync::atomic are the building blocks that mutexes, reference
counters, and lock-free data structures are themselves made of. By the end
of this module you will understand WHY Arc works — and when atomics beat
any lock.
The rhythm stays the same as in Module 12: first Predict (what does this program do?), then Run, then we sharpen the understanding. We start with the classic case: four threads, one counter — this time without a mutex.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
static COUNTER: AtomicUsize = AtomicUsize::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: {}", COUNTER.load(Ordering::Relaxed));
}
// → Counter: 4000
Predict: What does this print — always 4000, or sometimes less?
Run: Always exactly 4000. The reason: fetch_add is atomic —
indivisible. Reading, incrementing, and writing back happen as ONE CPU
instruction that no other thread can slip into. The naive counterpart
counter = counter + 1 on a shared value is three steps (load, add,
store) — two threads may overlap in them and updates get lost (the infamous
lost update from Module 12). fetch_add closes exactly that window.
The family at a glance: load/store read and write, swap exchanges and
returns the old value, and fetch_add, fetch_sub, fetch_and,
fetch_or, fetch_xor combine reading and writing in one go. Plus
AtomicBool for flags and AtomicI64/AtomicU64 for numbers — the catch
with all of them: they manage exactly ONE value. No two fields, no
invariants, no "state that belongs together".
What atomic really means
Ordering argument (Lesson 118) defines how much visibility is guaranteedCheck: Why does fetch_add never lose an update, while counter = counter + 1 on a shared value does?
Answer: fetch_add is one indivisible operation — no thread can slip between load and store
The plain increment is split into three observable steps (load, add, store); two threads can overlap and swallow an update. fetch_add turns the three steps into one CPU instruction.
⚠ Common mistake: Calling
fetch_add(1)without the second argument — the compiler rejects it with E0061 ("this method takes 2 arguments but 1 was supplied"), because every atomic method requires itsOrdering. AndCOUNTER += 1fails outright:AtomicUsizedoes not implementAddAssign— atomics are driven only throughfetch_*,load, andstore.
Takeaways:
The most powerful atomic operation is CAS — compare and swap. In Rust:
compare_exchange(expected, new, ok_ordering, err_ordering). It says:
write new only if the current value is still expected — and report
whether that worked. If it fails, you get back the value that was actually
found. From this you build the fundamental pattern of all lock-free
programming: the CAS loop.
use std::sync::atomic::{AtomicUsize, Ordering};
static STATE: AtomicUsize = AtomicUsize::new(3);
fn double_below_hundred() -> usize {
let mut current = STATE.load(Ordering::Relaxed);
loop {
if current >= 100 {
return current;
}
match STATE.compare_exchange(
current,
current * 2,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return current * 2,
Err(seen) => current = seen,
}
}
}
// → with STATE = 3: returns 6; with a racing thread STATE ends up at 6 or 12
Predict: Two threads call the function simultaneously, STATE is 3. What is in STATE afterwards — 6, 12, or both one after the other?
Run: 6 or 12, depending on who CASes first. That is exactly the point:
no thread waits for another. The loser of the race is sent back into the
loop via the Err branch with the fresh value — no lock, just another try.
The Err case is not an error but the normal-flow instruction "someone was
faster, try again".
The same pattern drives the smallest of all locks: the spinlock. Instead of blocking, it spins in place until the flag flips:
use std::sync::atomic::{AtomicBool, Ordering};
pub struct Spinlock(AtomicBool);
impl Spinlock {
pub fn new() -> Self {
Spinlock(AtomicBool::new(false))
}
pub fn lock(&self) {
while self
.0
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
std::hint::spin_loop(); // busy-wait — burns CPU cycles
}
}
pub fn unlock(&self) {
self.0.store(false, Ordering::Release);
}
}
CAS asks "is the value still A?" — not "has nothing changed since?". Thread A reads value A and gets parked. Thread B changes A to B and then back to A. When A resumes, the CAS succeeds — even though the state may have fundamentally changed in between. For simple counters this is harmless; for pointers into reused nodes (lock-free stacks, queues) it leads to real corruption. The ecosystem answer is epoch-based memory management (crossbeam, Lesson 120); in safe Rust with plain numeric atomics you will practically never meet ABA.
The CAS loop as a mental model
Check: What does the Err case of compare_exchange mean in a CAS loop?
Answer: Another thread wrote in the meantime — you get the fresh value and retry
Err returns the value that was actually found. The loop carries it forward as the new expected value — progress without blocking.
⚠ Common mistake: Replaying the CAS loop in the
Errbranch with the stale local value instead of adopting the returned one (forgettingcurrent = seen). Then every round compares against an already-outdated value, the CAS can never succeed again — the loop spins forever. TheErrpayload is the fresh value, not an error message.
Takeaways:
Both the compiler and the CPU may reorder instructions — as long as the result within a single thread looks like everything happened in program order. Across threads that does not hold: without a contract, thread B may observe the writes of thread A in almost arbitrary order. Exactly this contract is defined by the memory orderings.
The key term is happens-before: when one thread stores a value with
Release and another loads the same value with Acquire and sees it
there, then ALL writes that happened before the Release are also visible
to the reading thread. Release-Acquire is a one-way street for visibility —
paired over the same atomic value.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
static READY: AtomicBool = AtomicBool::new(false);
static DATA: AtomicUsize = AtomicUsize::new(0);
fn main() {
std::thread::scope(|s| {
s.spawn(|| {
DATA.store(42, Ordering::Relaxed); // 1) write the data
READY.store(true, Ordering::Release); // 2) set the flag — fence
});
s.spawn(|| {
while !READY.load(Ordering::Acquire) {
std::hint::spin_loop();
}
// Acquire pairs with Release: DATA is guaranteed to be 42
assert_eq!(DATA.load(Ordering::Relaxed), 42);
});
});
}
Predict: Would this also work if BOTH operations were Relaxed?
Run: No — not guaranteed. Relaxed guarantees only atomicity, no ordering. The reading thread could see the flag as true while DATA is still 0. This is the classic bug: atomic flags without matching orderings are no release for the data behind them.
| Ordering | Contract |
|---|---|
Relaxed | Atomicity only, no ordering guarantees — good for counters, statistics |
Release | Store: all previous writes may not sink below it |
Acquire | Load: no subsequent reads/writes may be hoisted above it |
AcqRel | For read-modify-write: Acquire on the load, Release on the store |
SeqCst | One global total order over all SeqCst operations — costly, but delightfully simple |
Rule of thumb to start: Relaxed for pure counters without dependent
data, Release/Acquire as a pair for flag hand-offs with data behind
them, SeqCst when you are unsure or combining several flags —
correctness beats the last microsecond.
Release and Acquire are a pair
Check: A thread writes data and then sets a flag with Relaxed. Another thread sees the flag and reads the data. What can happen?
Answer: It sees the flag, but possibly still the old data
Relaxed only guarantees atomicity, not ordering. For the data behind the flag to be visible you need Release on the write and Acquire on the read.
⚠ Common mistake: Swapping the roles — putting
Acquireon the store andReleaseon the load. The pair works in one direction only: Release belongs to the write, Acquire to the read; flipped, no happens-before is established, and the reading thread may keep seeingDATA = 0— with no warning from the compiler.
Takeaways:
Module 12 introduced Arc as thread-safe ownership — with an atomic
reference counter, as you now know. The natural combination: an
Arc<AtomicBool> as a shared stop flag that many workers read and one
controller writes.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let stop = Arc::new(AtomicBool::new(false));
let handles: Vec<_> = (0..3)
.map(|_| {
let flag = Arc::clone(&stop);
thread::spawn(move || {
let mut work = 0u64;
while !flag.load(Ordering::Relaxed) {
work = work.wrapping_add(1); // do work ...
}
work
})
})
.collect();
stop.store(true, Ordering::Relaxed); // signal everyone
for h in handles {
h.join().unwrap();
}
}
Predict: Why does the flag need to live in an Arc — isn't the AtomicBool itself thread-safe?
Run: Because this is about ownership, not atomicity.
thread::spawn requires 'static data; a raw &AtomicBool could outlive
the spawning function. Arc distributes shared ownership of the flag — the
atomicity of the operations is independent of that. Both mechanisms solve
different problems, which is why they stack cleanly. The signal itself only
needs Relaxed here: stopping may arrive a few loop iterations later —
there is no further data hanging behind it.
Lock-free programming is not an endgame you must reach. The mutex stays the right choice when ...
lock().unwrap(); a finely
tuned ordering combination needs a discussion.Atomic protects a value, Mutex protects a relationship
Check: Why does the shared stop signal need Arc, even though AtomicBool operates thread-safely on its own?
Answer: Arc provides the shared ownership that thread::spawn needs for 'static data
Atomicity and ownership are separate problems: AtomicBool makes single operations indivisible, Arc distributes ownership of the flag across threads. The two stack cleanly.
⚠ Common mistake: Moving the
Arcinto severalthread::spawnclosures — the compiler reports E0382 ("use of moved value"). Take a fresh copy before each spawn:let flag = Arc::clone(&stop);inside the loop — that costs a reference-count bump, not a deep copy.
Takeaways:
The standard atomics are the raw material; two crates build the tools you will actually find in production code:
crossbeam is THE lock-free ecosystem package: channels with select!,
deque and queue data structures without a global lock, and underneath it an
epoch-based memory management — the practical answer to the ABA problem
from Lesson 117: nodes are only freed once no reader can still look inside.
Exactly the part you do not want to build yourself.
arc-swap solves a different everyday case: a configuration that many
threads read constantly and that a single writer rarely swaps.
ArcSwap<T> allows replacing the Arc content without a lock — readers keep
working with the old Arc undisturbed, which is freed by the last reader.
Perfect for hot-reload configurations.
Scenario: The metric counter under load
What you take away from the deep dive
Check: Which problem does crossbeam's epoch-based memory management solve?
Answer: The ABA problem — nodes are freed only when no reader can access them anymore
Epochs defer freeing nodes until no reader can possibly look inside anymore — so value A in a CAS can no longer be a reused stale node.
⚠ Common mistake: Treating
ArcSwap::load()like anArc<T>— the method returns only a short-livedGuardthat you cannot stash in structs or hold across an.await. If you need an owned Arc, useload_full().
Takeaways:
Course navigation: ← Module 22 · All 27 modules · Module 24 →