skip to content

In Rust, how do you write a toy spin lock on an `AtomicBool`, and which orderings do its acquire and release steps need?

level: seniorimportance: should knowfreq 35%

answer

  1. flag plus UnsafeCell
  2. win false to true with Acquire
  3. unlock store with Release
  4. spin_loop is a CPU hint
  5. Sync needs an unsafe impl

basics

~20 s

Pair an AtomicBool with an UnsafeCell<T>; lock by winning compare_exchange_weak(false, true, Acquire, Relaxed) in a loop that calls hint::spin_loop, and unlock with store(false, Release). Relaxed on either step lets critical sections overlap, which is a data race.

solid answer

~40 s

The lock is a struct holding `locked: AtomicBool` and `value: UnsafeCell<T>`, plus `unsafe impl<T: Send> Sync`, because `UnsafeCell` makes the struct `!Sync` and only you know the flag serialises access. Locking loops on `compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)`, calling `std::hint::spin_loop()` between attempts; winning the exchange with `Acquire` makes the previous holder's writes visible. Unlocking is `store(false, Ordering::Release)`, which publishes this holder's writes to the next `Acquire`. With `Relaxed` the flag still excludes threads but the data does not follow it, and Miri reports a data race. Release the flag from a guard's `Drop` so a panic cannot leave it locked. In production code use `std::sync::Mutex`, which on Linux already tries the same `Acquire`/`Relaxed` `compare_exchange`, spins briefly, then parks the thread.

code

rust · 36 lines
rust
use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{hint, thread};

struct SpinLock<T> {
    locked: AtomicBool,
    value: UnsafeCell<T>,
}
// SAFETY: the flag hands out one &mut T at a time, so T only has to be Send
unsafe impl<T: Send> Sync for SpinLock<T> {}

impl<T> SpinLock<T> {
    const fn new(value: T) -> Self {
        SpinLock { locked: AtomicBool::new(false), value: UnsafeCell::new(value) }
    }
    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        while self.locked.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
            hint::spin_loop();
        }
        // SAFETY: we won the false -> true exchange, so no other thread holds the value
        let r = f(unsafe { &mut *self.value.get() });
        self.locked.store(false, Ordering::Release);
        r
    }
}

static TOTAL: SpinLock<u64> = SpinLock::new(0);

fn main() {
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| for _ in 0..1000 { TOTAL.with(|t| *t += 1) });
        }
    });
    println!("{}", TOTAL.with(|t| *t)); // 4000
}

go deeper

for a junior

Recall the shape: an AtomicBool flag, a loop that sets it from false to true, and a store of false to unlock.

for a middle

Explain why the data sits in an UnsafeCell, why the struct needs an unsafe impl of Sync, and what compare_exchange_weak returns in the loop.

for a senior

Justify Acquire on the winning exchange and Release on the unlock, show the Relaxed version is a data race Miri catches, and fix the panic path with a guard.

for a principal

Explain why a team ships std::sync::Mutex rather than a spin lock, and the narrow places such as bare-metal code where spinning is defensible.

## The parts of the lock A spin lock is the smallest lock you can build from an atomic, which is why interviewers ask for one: it forces every ordering decision into the open. It needs three pieces. - **`locked: AtomicBool`** — `false` means free, `true` means held. - **`value: UnsafeCell<T>`** — the protected data. The lock hands out `&mut T` from `&self`, which is mutation through a shared reference, and `UnsafeCell` is the only legal way to do that. A plain `T` field cannot legally be mutated through `&self` at all. - **`unsafe impl<T: Send> Sync for SpinLock<T> {}`** — `UnsafeCell` makes the struct `!Sync`, so it cannot be put in a `static` or shared across threads until you assert that the flag serialises access. The bound is `T: Send`, the same one `std::sync::Mutex` uses, because the lock moves exclusive access to `T` between threads. What that promise means in general belongs with the material on `Send` and `Sync`. ## Acquiring ```rust while self .locked .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) .is_err() { std::hint::spin_loop(); } ``` 1. The exchange succeeds only for the thread that sees `false` and writes `true`, so at most one thread holds the lock. 2. **Success ordering `Acquire`**: the previous holder unlocked with a `Release` store of `false`; reading that value with `Acquire` makes everything the previous holder wrote to `value` happen-before this holder's accesses. 3. **Failure ordering `Relaxed`**: a failed attempt touches no protected data, so it needs no ordering. 4. **`compare_exchange_weak`** fits because the loop retries anyway; a spurious failure costs one spin. `swap(true, Ordering::Acquire)` returning `false` is an equally valid test. 5. **`std::hint::spin_loop()`** emits a CPU hint that the thread is busy-waiting. Its documentation contrasts it with `thread::yield_now`: it "does not interact with the operating system". While another thread holds the lock, every failed exchange still asks for the cache line in exclusive mode. Many implementations therefore add an inner loop that only reads the flag with `load(Ordering::Relaxed)` until it looks free, and retry the exchange only then; the reasoning behind that pattern belongs with general spin-lock material. ## Releasing `self.locked.store(false, Ordering::Release)`. `Release` orders every write the holder made to `value` before the store, so the next thread to win the exchange with `Acquire` sees them. A store cannot use `Acquire`: rustc's deny-by-default `invalid_atomic_ordering` lint rejects it with "atomic stores cannot have `Acquire` or `AcqRel` ordering". ## What goes wrong with `Relaxed` | Acquire step | Release step | Outcome | |---|---|---| | `Acquire` | `Release` | correct: critical sections are ordered | | `Relaxed` | `Release` | the winner may not see the previous holder's writes | | `Acquire` | `Relaxed` | the holder's writes are not published to the next winner | | `Relaxed` | `Relaxed` | mutual exclusion on the flag, no ordering on the data | The flag still admits one thread at a time with `Relaxed`, which is why the bug is easy to miss. But the protected value is non-atomic, and without the happens-before edge two holders' accesses are unordered — a data race, which is undefined behaviour. Running the counter example below under Miri with both orderings changed to `Relaxed` stops with "Undefined Behavior: Data race detected" at the `&mut *self.value.get()` line; with `Acquire` and `Release` it runs clean. ## Panics and guards The `with(f)` shape in the example is short but fragile: if `f` panics, the `store(false, …)` never runs and every other thread spins forever. A real lock returns a guard type whose `Drop` performs the `Release` store, because unwinding runs destructors. That is the same reason `std::sync::Mutex` returns a `MutexGuard`. ## Why not ship it The toy lock spins without limit, which wastes a core and behaves badly when the holder is descheduled. The `spin_loop` documentation itself recommends ending a spin "after a finite amount of iterations" and making a blocking call. `std::sync::Mutex` does exactly that: on Linux and Windows its implementation tries `compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed)`, spins a bounded number of times, then sleeps on a futex. The trade-offs of spinning versus parking in general belong with concurrency fundamentals; in a Rust codebase the practical rule is to reach for `Mutex` and keep a hand-written spin lock to interviews, teaching code and environments with no OS to park on.

  • Why does the struct need `unsafe impl<T: Send> Sync` and not `T: Sync`?
    The lock gives one thread at a time exclusive `&mut T` access, which effectively moves the value between threads, so `T: Send` is required. Threads never share `&T` simultaneously through it, so `T: Sync` is not needed. `std::sync::Mutex<T>` uses the same `T: Send` bound for its `Sync` impl.
  • Is `self.locked.swap(true, Ordering::Acquire)` a correct replacement for the `compare_exchange_weak` call?
    Yes. `swap` returns the previous value, and the caller holds the lock when that value is `false`. `Acquire` on the swap gives the same visibility of the previous holder's writes. Writing `true` over an already-`true` flag is harmless, though under contention it keeps bouncing the cache line, which is why spin loops often check with a `Relaxed` load before trying.

  • Relaxed is enough on the lock flag because the exchange is atomic.
  • The unlock store should use Acquire so the next thread sees the data.
  • hint::spin_loop yields the thread to the operating system scheduler.
  • A spin lock is generally faster than std::sync::Mutex.
  • A plain T field works because the flag already guards it.