patternModeratepending
Lock-free concurrent data structures — when and how to use atomics
Viewed 0 times
lock-freeatomicCAScompare-and-swapmemory orderingmutex contentioncrossbeam
linuxmacos
Problem
Mutex-based concurrent code has contention issues — threads spend more time waiting for locks than doing work. Performance doesn't scale with more threads. Priority inversion or deadlocks occur under load.
Solution
(1) Use atomics for simple counters and flags: AtomicUsize, AtomicBool (Rust), Atomic* (Java), Atomics (JS SharedArrayBuffer). (2) Compare-and-swap (CAS) loop for lock-free updates: load current value, compute new value, CAS to set it, retry if another thread changed it. (3) Use concurrent data structures from libraries: crossbeam (Rust), ConcurrentHashMap (Java), concurrent.futures (Python). (4) Memory ordering matters: use Relaxed for counters, Acquire/Release for synchronization points, SeqCst when unsure. (5) Don't roll your own lock-free data structures unless you're an expert — use battle-tested libraries. (6) Profile first: mutexes are fine for most workloads. Lock-free is only worth the complexity under high contention.
Why
Mutexes serialize access — only one thread enters the critical section. Under high contention, threads queue up. Atomics allow multiple threads to operate simultaneously, failing and retrying only on actual conflicts.
Revisions (0)
No revisions yet.