What is Lock-free algorithm?
A property of an algorithm that some thread can always make progress even if others stall partway. Built with atomic instructions such as CAS.
Japanese name: ロックフリー
A property of an algorithm that some thread can always make progress even if others stall partway. Built with atomic instructions such as CAS.
Japanese name: ロックフリー
In a program that uses locks, if the operating system suspends a thread holding a lock, every thread waiting for that lock is stuck. Lock-free is the property that, whichever thread stops wherever, someone always makes progress in the system as a whole. There is also a stronger guarantee, called wait-free: every thread always completes its operation within a bounded number of steps.
The basic form is a loop using CAS. The thread first reads the current value and computes a new value from it. It then uses CAS to replace the value only if it is still what was read. If another thread has changed it first, the CAS fails and the thread starts over. That one thread failed means another succeeded, so the system as a whole always progresses.
If a value changes and then returns to its original value, the change goes unnoticed. Deciding when it is safe to free data that another thread may still be looking at is also a hard problem. Under heavy contention, a thread may do nothing but retry and end up slower than with a lock. The benefits are that deadlock cannot occur and that the whole does not stop when a thread is suspended. It can also be used where waiting for a lock is not possible, as inside interrupt handling. Building it correctly is difficult, so using an existing, verified library is the safe choice.
Answer: A. Even if some thread stops partway, at least one of the other threads can still make progress
With locks, if the holder is stalled by an interrupt or low priority, everyone else waits. A lock-free algorithm updates shared data directly with CAS or similar, arranged so that a thread fails and retries only when some other thread has succeeded. As a whole, some thread always makes progress. Building one correctly is hard, though, and pitfalls such as the ABA problem must be handled.
Not necessarily. What lock-free guarantees is that the whole always progresses, not speed. Where contention is low, a simple lock can be faster.
No. A library may implement atomic variables of large types with a lock internally. A way to query whether an implementation is lock-free is provided.
As an Amazon Associate I earn from qualifying purchases.
This page was drafted with AI and fact-checked by a separate AI review before publication. Our Editorial policy explains how we write and check content. If you spot an error, please tell us on our Contact page.