Lock-Free
ELI5 - The Vibe Check
Lock-free code gets multiple threads to safely share data without ever making anyone stand in line waiting for a lock. Instead of grab the key, do your work, hand back the key, threads use special atomic CPU instructions to make their change in one uninterruptible step, and if another thread got there first, they just retry instead of blocking.
Real Talk
A lock-free data structure or algorithm guarantees system-wide progress, meaning at least one thread always makes forward progress, without ever using blocking locks, typically implemented using atomic compare-and-swap operations in a retry loop. It avoids problems like deadlock and priority inversion inherent to locks, at the cost of significantly more complex code and subtle correctness pitfalls like the ABA problem.
Show Me The Code
// Lock-free increment using compare-and-swap
for {
old := counter.Load()
if counter.CompareAndSwap(old, old+1) {
break
}
}
When You'll Hear This
"We rewrote the queue as lock-free and the tail latency spikes disappeared." / "Lock-free code is faster under contention but debugging it will humble you."
Related Terms
Data Race
A data race is what happens when two threads touch the exact same piece of memory at the exact same time, and at least one of them is writing, with nothing...
Lock Contention
Lock contention is what happens when a mutex becomes the most popular door in the building, and instead of doing useful work, half your threads are just st...
Memory Ordering
Memory ordering is the unsettling fact that the order you wrote your instructions and the order the CPU and compiler actually carry them out are not the sa...
Mutex
A mutex is a single key to a single bathroom.