Every multi-threaded program eventually needs a queue: one side produces work, the other side consumes it. The obvious solution wraps the queue in a mutex — a lock that only one thread may hold at a time. Simple, but costly: if the consumer is slow, the producer waits. If the producer crashes while holding the lock, everyone waits forever.
Lock-free data structures remove that dependency. Instead of a lock, every operation reads the shared state, computes the desired new state, and then calls compare-and-swap (CAS) — a single CPU instruction that atomically writes the new value only if the old value is still there. If another thread changed the state first, CAS fails and the caller simply retries. No thread ever blocks; progress is guaranteed system-wide.
The landmark design is the Michael-Scott queue (1996), a singly-linked list where both enqueue and dequeue use exactly one CAS each. It ships inside the Java Virtual Machine, the Linux kernel, and countless high-performance systems today.
Comments
Loading comments...