Lock-free programming is a technique in concurrency for building shared data structures and algorithms that coordinate threads through atomic operations instead of locks. Its defining guarantee is system-wide progress: whenever several threads operate on the structure, at least one of them completes its operation in a finite number of steps, even if other threads are delayed, preempted or stopped.
In everyday programming the term is often used loosely for any non-blocking algorithm, but the formal definition is narrower and sits within a hierarchy of progress guarantees. A lock-free data structure avoids the classic failure modes of mutual exclusion, such as deadlock and priority inversion, at the price of considerably harder design and verification.
How lock-free algorithms make progress
A lock-free algorithm replaces the critical section with a read, compute and publish loop. A thread reads the current shared state, prepares a new state privately, and then attempts to install it with a single atomic instruction, most commonly compare-and-swap (CAS). The CAS succeeds only if the shared value still equals what the thread originally read; otherwise the thread retries with fresh data.
A failed CAS always means that another thread succeeded, which is precisely why the whole system keeps moving. No thread ever holds a resource that others must wait for, so a thread that is suspended in the middle of its work cannot block anyone else. The same property makes lock-free code safe to call from contexts where blocking is forbidden, such as some signal handlers and interrupt paths.
The hardware primitives that make this possible differ between architectures, as the following table summarizes.
| Primitive | Semantics | Typical availability |
|---|---|---|
| Compare-and-swap | Writes a new value only if the old one matches | x86 CMPXCHG, ARMv8.1 CAS |
| Load-linked / store-conditional | Store fails if the location changed since the load | ARM LDXR/STXR, POWER, RISC-V |
| Fetch-and-add | Atomically adds and returns the previous value | x86 LOCK XADD, most modern ISAs |
| Atomic exchange | Swaps in a new value and returns the old one | Nearly universal |
| Double-width CAS | Compares and swaps two adjacent words | x86-64 CMPXCHG16B, limited elsewhere |
Progress guarantees compared
Lock-freedom is one of several progress conditions that describe how a concurrent algorithm behaves under contention and scheduling delays. Understanding the hierarchy prevents the common mistake of calling any lock-avoiding code lock-free.
| Guarantee | What it promises | Typical cost |
|---|---|---|
| Wait-free | Every thread finishes in a bounded number of steps | Highest complexity, often slower on average |
| Lock-free | At least one thread always finishes | Individual threads may starve |
| Obstruction-free | A thread finishes if it runs in isolation | Livelock possible under contention |
| Blocking (lock-based) | Progress depends on the lock holder running | Deadlock and priority inversion possible |
The distinction matters in practice. A lock-free queue can still let one unlucky thread retry indefinitely while others succeed, so it guarantees throughput, not fairness. Real-time systems that need a bound on every operation must look to wait-free designs, which are rarer and frequently built on top of lock-free fast paths with a helping mechanism.
Memory ordering and the ABA problem
Correct lock-free code depends on memory ordering, not only on atomicity. Compilers and processors reorder loads and stores for performance, so a thread could observe a published pointer before the data it points to is visible. Languages expose this through memory models: C++11 and C11 define orders such as memory_order_acquire, memory_order_release and memory_order_seq_cst, while Java relies on volatile fields and the VarHandle API.
The ABA problem is the best-known trap. A thread reads value A, is preempted, and meanwhile another thread changes the value to B and back to A, perhaps by freeing and reallocating a node at the same address. The first thread’s CAS then succeeds although the structure has changed underneath it. Standard defenses include tagged pointers with version counters, double-width CAS and safe memory reclamation.
Memory reclamation is in fact the hardest part of lock-free design in languages without garbage collection, because a node cannot be freed while another thread might still read it.
| Scheme | Idea | Main drawback |
|---|---|---|
| Hazard pointers | Threads announce pointers they are reading | Per-access overhead and fences |
| Epoch-based reclamation | Memory is freed after all threads pass an epoch | One stalled thread delays all frees |
| Reference counting | Atomic counters track live readers | Contention on shared counters |
| Read-copy-update (RCU) | Old versions are freed after a grace period | Best for read-mostly workloads |
| Garbage collection | The runtime tracks reachability | Pauses and runtime dependency |
Where lock-free programming fits
Lock-free techniques pay off where contention is high, latency spikes are unacceptable or blocking is impossible. Typical examples are single-producer single-consumer ring buffers in audio and trading systems, work-stealing deques in task schedulers, concurrent hash maps, reference counters and statistics collectors. Mature libraries such as Java java.util.concurrent, the Rust crossbeam crates and Intel oneTBB already provide well-tested lock-free containers.
The decision table below compares lock-free structures with the alternatives a developer usually considers.
| Situation | Recommended approach | Reason |
|---|---|---|
| Low contention, simple invariants | Mutex | Simpler and usually just as fast |
| Very short critical sections | Spinlock or atomic counter | Avoids kernel calls |
| Hot queue between threads | Proven lock-free queue | Removes convoying and preemption stalls |
| Read-mostly shared data | RCU or copy-on-write | Readers never wait |
| Hard real-time deadlines | Wait-free structure | Bounds every operation |
Risks and common mistakes
The most serious risk is subtle incorrectness. Lock-free bugs depend on rare interleavings, so they may pass millions of test runs and still fail in production. Verification tools such as ThreadSanitizer, model checkers like CDSChecker or Loom for Rust, and formal reasoning about linearizability are standard practice for any custom design.
- Assuming lock-free means faster. Heavy CAS retry traffic and cache-line bouncing can make a lock-free structure slower than a good mutex.
- Ignoring false sharing. Independent atomics on the same cache line, typically 64 bytes, contend as if they were one variable.
- Using relaxed ordering everywhere. Weak orders are correct only with careful reasoning; sequential consistency is the safe default.
- Writing custom structures needlessly. A vetted library implementation is almost always the better engineering choice.
The simple explanation
Imagine several people editing a shared whiteboard. With a lock, only the person holding the marker may write, and everyone else waits, even if the marker holder wanders off for coffee.
Lock-free programming removes the marker. Each person looks at the board, prepares a change on a notepad, and then writes it only if the board still looks the way it did a moment ago. If someone else got there first, the person simply looks again and retries. Somebody always makes progress, and nobody can freeze the whole room by walking away. The catch is that the rules must be designed very carefully, or changes can quietly overwrite each other.
How it is used in practice
A team building a real-time audio application must pass control messages from the user interface thread to the audio thread, which renders a buffer of 128 samples at 48 kHz, leaving under 3 milliseconds per callback. Their first version used a mutex-protected queue, and occasional audible clicks appeared whenever the operating system preempted the interface thread while it held the lock.
The engineers replaced the queue with a single-producer single-consumer ring buffer built on atomic head and tail indices with acquire and release ordering. The audio thread now reads messages without ever waiting, and the interface thread only fails to enqueue when the buffer is full, which it handles by dropping redundant parameter updates.
After profiling under heavy load, the dropouts disappeared entirely, and the worst-case callback time fell well within the deadline. The team kept the mutex-based design for non-real-time paths, where its simplicity outweighed any performance gain.