6. Synchronization primitives
One-liner. Atomics order single words; locks protect invariants; futexes make waiting cheap.
Memorize
- Atomic ops (CAS, fetch-add) are lock-free but only protect one word.
- Spinlock: busy-waits — correct only for very short critical sections, never across sleep.
- Mutex: sleeps via futex (fast userspace check, kernel wait queue on contention).
- Semaphore: counts permits; RW lock: many readers or one writer.
- RCU: readers lock-free, writers wait for a grace period — great for read-mostly kernel data.
- Memory barriers (
smp_mb, acquire/release) constrain reordering; atomics imply ordering only if you use the right variant. - Contention shows up as PSI stall time and involuntary context switches.
Trap. Using a spinlock or atomic to protect a multi-step invariant. Do this. Protect the invariant with one lock; atomics are for counters and flags.
Check
What makes a futex-based mutex cheap when uncontended?
Why
The fast path is a single atomic compare-and-swap in user space; the kernel is only involved when a waiter must sleep.