Concurrent Stacks & Queues
Lock-free Treiber stacks, Michael–Scott queues and the ABA problem.
Two threads push onto the same stack at the same instant. With a lock, one of them waits, and if the lock holder is descheduled, everyone waits. Without a lock, a single hardware instruction, compare-and-swap, lets one push succeed and tells the other to retry. The resulting stack fits in a dozen lines, but proving it correct needs a new definition of what "correct" means when operations overlap in time.
What you’ll learn
- Define linearizability, and decide whether a concurrent history of a queue is linearizable.
- Implement Treiber's lock-free stack with compare-and-swap, locate its linearization points, and prove that it is lock-free but not wait-free.
- Reproduce the ABA problem, and compare tagged pointers, hazard pointers, epoch-based reclamation and garbage collection as fixes.
- Explain the Michael–Scott queue, including its dummy node and its helping step.
- Rank synchronization primitives by consensus number, and deduce which objects cannot be built wait-free from which.
What does correct mean when operations overlap?
A sequential queue is easy to specify: a dequeue returns the oldest item. A concurrent queue is used by many threads at once, and their operations overlap in time. Each operation has an invocation and a response, and a history records these events in real-time order. If operation responds before is invoked, precedes ; otherwise the two are concurrent, and either may take effect first.
Linearizability says that each operation appears to take effect instantaneously somewhere inside its own interval, which is what programmers intuitively expect of a "thread-safe" object. In particular it respects real time: if precedes , then 's point comes first.
Each history runs on a FIFO queue that starts empty; the intervals give each operation's invocation and response times. Which history is not linearizable?
- : enq(1) during ; : enq(2) during ; : deq() returns 2 during
- : enq(1) during ; : enq(2) during ; : deq() returns 2 during
- : enq(1) during ; : enq(2) during ; : deq() returns 2 during
- : enq(1) during ; : deq() returns 1 during
Show the answer
B. : enq(1) during ; : enq(2) during ; : deq() returns 2 during
In the second history, enq(1) responds before enq(2) is invoked, so every linearization puts 1 ahead of 2, and a dequeue that starts after both must return 1. In the first and third, the two enqueues overlap, so enq(2) may take effect first. In the fourth, the dequeue overlaps enq(1) and can take effect just after it.
Compare-and-swap and Treiber's stack
push(x):
n ← new node(x)
repeat
t ← top # read the current top
n.next ← t
until CAS(top, t, n) # linearization point of a push
pop():
repeat
t ← top
if t = null: return EMPTY # linearization point: reading null
nxt ← t.next
until CAS(top, t, nxt) # linearization point of a successful pop
return t.valueTreiber's stack (IBM, 1986): a singly linked list whose head pointer top changes only by CAS. A thread prepares its change privately and publishes it with one CAS; if another thread changed top in between, the CAS fails and the thread retries with the new top.
Lock-freedom buys robustness, not speed. A descheduled or crashed thread can never block the others, as it can while holding a lock, but every operation still fights over a single memory word, and under heavy contention most CAS attempts fail. The elimination backoff stack (Hendler, Shavit & Yerushalmi, 2004) lets a push and a pop that collide in a side array cancel out without touching top at all. The pop simply takes the pushed value, which is a valid linearization, because a push immediately followed by a pop leaves the stack unchanged.
The ABA problem and safe memory reclamation
CAS compares values, here addresses, and an address can come back. Suppose the stack holds A → B → C, and the memory of popped nodes is recycled:
| Step | Thread | Action | Stack afterwards |
|---|---|---|---|
| 1 | starts a pop: reads top = A and nxt = B, then is descheduled | A → B → C | |
| 2 | pops A; A's memory is freed | B → C | |
| 3 | pops B; B's memory is freed | C | |
| 4 | pushes a new item X, and the allocator hands it A's old address | X (at A's address) → C | |
| 5 | resumes: CAS(top, A, B) succeeds, because top holds address A again | top = B, a freed node; X and C are lost |
top went from A to B to C and back to A, so the CAS could not tell that anything had happened: the ABA problem.| Fix | Idea | Cost and caveats |
|---|---|---|
| Tagged pointers | Pair top with a version counter that every change increments, and compare both with a double-width CAS (or pack them into one word) | Cheap; fails only if the counter wraps around while a thread sleeps |
| LL/SC | The store-conditional fails if the word was written at all since the load-linked, whatever value it now holds | Hardware support varies, failures can be spurious, and some machines restrict what may run between the two instructions |
| Hazard pointers (Michael, 2004) | Before dereferencing t, a thread publishes it in a hazard slot and rechecks top; a retired node is freed only when no hazard slot points to it | A bounded number of unreclaimed nodes, but a store and a memory fence on every protected read |
| Epoch-based reclamation (Fraser, 2004) | Free a retired node only after every thread has passed a quiescent point since it was retired | Very cheap reads, but one stalled thread blocks all reclamation |
| Garbage collection | A node is never recycled while any thread still holds a reference to it | Prevents ABA through reuse automatically, at the price of a collector |
Think first Why is Treiber's stack immune to this scenario in a garbage-collected language such as Java?
Thread still holds a reference to node A, so the collector cannot reclaim A, and no new node can receive its address. X gets a different address, 's CAS sees a different top and fails, and retries correctly. That is why Java's lock-free collections need no hazard pointers, whereas in C and C++ the reclamation scheme is part of the algorithm.
The Michael–Scott queue
A queue has two hot spots: enqueues change the tail and dequeues change the head. Michael and Scott (1996) built a lock-free queue on a singly linked list that always begins with a dummy node, so the list is never empty and head and tail are never null. The queue is empty when head.next is null.
enqueue(x):
n ← new node(x, next = null)
loop
t ← tail; nxt ← t.next
if t = tail: # are t and nxt still consistent?
if nxt = null:
if CAS(t.next, null, n): # linearization point of an enqueue
CAS(tail, t, n) # swing tail; failure is harmless
return
else:
CAS(tail, t, nxt) # help: tail is lagging, advance it
dequeue():
loop
h ← head; t ← tail; nxt ← h.next
if h = head:
if h = t:
if nxt = null: return EMPTY # linearization point: reading null
CAS(tail, t, nxt) # help a lagging tail first
else:
v ← nxt.value # read before the CAS: nxt may be retired after it
if CAS(head, h, nxt): # linearization point of a dequeue
return v # nxt is the new dummy; h can be retiredAn enqueue links its node with one CAS and then swings tail with a second. Between the two, tail lags one node behind, and any thread that notices (t.next is not null) helps by advancing it before doing its own work. No thread ever waits for another to finish, which is what makes the queue lock-free.
Java's ConcurrentLinkedQueue is based on the Michael–Scott algorithm. Without garbage collection, the queue needs the same reclamation care as the stack: the original paper used counted (tagged) pointers, and Michael's hazard pointers were later shown to work on this very queue.
Progress guarantees and the consensus hierarchy
| Progress condition | Guarantee | Example |
|---|---|---|
| Wait-free | every operation finishes within a bounded number of its own steps, whatever the other threads do | an atomic counter built on a fetch-and-add instruction |
| Lock-free | some operation finishes within a bounded number of steps of the whole system: no deadlock or livelock, but one thread may starve | Treiber's stack, the Michael–Scott queue |
| Obstruction-free | an operation finishes if it eventually runs alone for long enough (Herlihy, Luchangco & Moir, 2003) | their obstruction-free deque, and some software transactional memories |
| Blocking | progress depends on lock holders being scheduled; at best deadlock-free or starvation-free | a queue guarded by a mutex |
A queue solves 2-thread consensus. Start the queue as [WIN, LOSE]. Each thread writes its proposal to its own register and then dequeues once. The thread that gets WIN decides its own proposal; the other decides the winner's, which it reads from the winner's register.
CAS solves -thread consensus. A shared word starts as . Each thread runs one CAS from to its proposal and then decides whatever the word holds: the first CAS wins for everybody.
Registers cannot solve 2-thread consensus. A valency argument in the style of Fischer, Lynch and Paterson: some reachable state is bivalent (both decisions still possible), while every next step of either thread makes it univalent. A case analysis of those two steps, reads and writes of registers, always yields two states that one of the threads cannot tell apart but that must lead to different decisions. The same argument, with more cases, shows that queues cannot solve consensus for 3 threads.
So no wait-free queue for two or more threads can be built from reads and writes alone, and no wait-free CAS for three or more threads can be built from queues. With CAS, every object has a wait-free implementation, but the universal construction is slow, so practical designs are crafted by hand. Kogan and Petrank (2011) gave a wait-free queue for any number of enqueuers and dequeuers, in which threads help announced operations; LCRQ (Morrison & Afek, 2013) built a fast lock-free queue on fetch-and-add over ring buffers; and Yang and Mellor-Crummey (2016) gave a wait-free queue as fast as fetch-and-add itself.
Key takeaways
- Linearizability: each operation appears to take effect at one instant inside its interval, consistently with real-time order. It is local, so linearizable objects compose.
- Treiber's stack publishes each change with one CAS on
top. A failed CAS means another operation succeeded, so the stack is lock-free, though not wait-free. - CAS compares addresses, and recycled addresses cause the ABA problem; tagged pointers, LL/SC, hazard pointers, epochs or garbage collection prevent it.
- The Michael–Scott queue uses a dummy node and two CASes per enqueue, and any thread that finds the tail lagging helps advance it.
- Consensus numbers rank primitives: registers 1; queues, stacks, test-and-set and fetch-and-add 2; CAS infinity. No wait-free queue can be built from registers alone, and CAS is universal.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Thread 's enqueue(1) completes; then thread 's enqueue(2) starts and completes; then thread dequeues and gets 2. Nothing else happens. Is this history linearizable?
- Yes: 's operation may take effect first
- No: 's operation precedes 's in real time, so 1 must come out first
- Yes, provided 's dequeue overlaps 's enqueue
- It depends on the hardware's memory model
Show the answer
B. No: 's operation precedes 's in real time, so 1 must come out first
Linearization points must respect real-time precedence. Enqueue(1) responded before enqueue(2) was invoked, so 1 is ahead of 2 in every linearization, and a dequeue that starts afterwards must return 1.
Why is Treiber's stack lock-free but not wait-free?
- Its CAS can fail spuriously, even when nobody else touched
top - It uses a lock internally on the
toppointer - A failed CAS means another operation's CAS succeeded, so the system progresses, but one thread can keep losing forever
- It is wait-free: every push and pop takes a bounded number of steps
Show the answer
C. A failed CAS means another operation's CAS succeeded, so the system progresses, but one thread can keep losing forever
Every failure is paid for by another thread's success, which gives system-wide progress: lock-freedom. Nothing bounds how many times one particular thread loses the race, so an individual operation can starve.
Which fix makes Treiber's pop fail its CAS when top was changed and then changed back to the same address?
- Pairing
topwith a version counter that every successful update increments, and comparing both in one double-width CAS - Retrying the CAS a second time
- Reading
toptwice before the CAS - Declaring
topvolatile
Show the answer
A. Pairing top with a version counter that every successful update increments, and comparing both in one double-width CAS
The counter makes "A again" distinguishable from "A": between 's read and its CAS the counter has moved on, so the CAS fails and retries. Hazard pointers solve the problem differently, by preventing the reuse itself.
Why can no wait-free FIFO queue for two threads be built from read/write registers alone?
- Registers are too slow
- Registers cannot store pointers
- It can: the Michael–Scott queue uses only reads and writes
- A queue solves 2-thread consensus and registers cannot, so a wait-free queue built from registers would solve consensus with registers
Show the answer
D. A queue solves 2-thread consensus and registers cannot, so a wait-free queue built from registers would solve consensus with registers
With a queue initialized to [WIN, LOSE], two threads reach consensus. If registers could implement the queue wait-free, they would solve 2-thread consensus, contradicting Herlihy's result that registers have consensus number 1.
Further reading
- M. P. Herlihy & J. M. Wing, "Linearizability: A correctness condition for concurrent objects," ACM Transactions on Programming Languages and Systems 12(3) (1990), 463–492.
- M. Herlihy, "Wait-free synchronization," ACM Transactions on Programming Languages and Systems 13(1) (1991), 124–149.
- M. M. Michael & M. L. Scott, "Simple, fast, and practical non-blocking and blocking concurrent queue algorithms," Proceedings of the 15th ACM Symposium on Principles of Distributed Computing (1996), 267–275.
- M. M. Michael, "Hazard pointers: Safe memory reclamation for lock-free objects," IEEE Transactions on Parallel and Distributed Systems 15(6) (2004), 491–504.
- M. Herlihy, N. Shavit, V. Luchangco & M. Spear, The Art of Multiprocessor Programming, 2nd ed. (Morgan Kaufmann, 2020).