Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 AA responds before BB is invoked, AA precedes BB; 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 AA precedes BB, then AA's point comes first.

Check your understanding

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?

  1. AA: enq(1) during [0,4][0, 4]; BB: enq(2) during [1,2][1, 2]; CC: deq() returns 2 during [3,6][3, 6]
  2. AA: enq(1) during [0,1][0, 1]; BB: enq(2) during [2,3][2, 3]; CC: deq() returns 2 during [4,5][4, 5]
  3. AA: enq(1) during [0,3][0, 3]; BB: enq(2) during [0,3][0, 3]; CC: deq() returns 2 during [4,5][4, 5]
  4. AA: enq(1) during [0,1][0, 1]; CC: deq() returns 1 during [0.5,2][0.5, 2]
Show the answer

B. AA: enq(1) during [0,1][0, 1]; BB: enq(2) during [2,3][2, 3]; CC: deq() returns 2 during [4,5][4, 5]

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

text
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.value

Treiber'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:

StepThreadActionStack afterwards
1T1T_1starts a pop: reads top = A and nxt = B, then is descheduledA → B → C
2T2T_2pops A; A's memory is freedB → C
3T2T_2pops B; B's memory is freedC
4T2T_2pushes a new item X, and the allocator hands it A's old addressX (at A's address) → C
5T1T_1resumes: CAS(top, A, B) succeeds, because top holds address A againtop = 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.
FixIdeaCost and caveats
Tagged pointersPair 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/SCThe store-conditional fails if the word was written at all since the load-linked, whatever value it now holdsHardware 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 itA 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 retiredVery cheap reads, but one stalled thread blocks all reclamation
Garbage collectionA node is never recycled while any thread still holds a reference to itPrevents 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 T1T_1 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, T1T_1's CAS sees a different top and fails, and T1T_1 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.

text
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 retired

An 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 conditionGuaranteeExample
Wait-freeevery operation finishes within a bounded number of its own steps, whatever the other threads doan atomic counter built on a fetch-and-add instruction
Lock-freesome operation finishes within a bounded number of steps of the whole system: no deadlock or livelock, but one thread may starveTreiber's stack, the Michael–Scott queue
Obstruction-freean operation finishes if it eventually runs alone for long enough (Herlihy, Luchangco & Moir, 2003)their obstruction-free deque, and some software transactional memories
Blockingprogress depends on lock holders being scheduled; at best deadlock-free or starvation-freea queue guarded by a mutex
DerivationProof sketch
  1. deq()=WIN⇒decide your own value,deq()=LOSE⇒decide the other’s\text{deq}() = \text{WIN} \Rightarrow \text{decide your own value}, \qquad \text{deq}() = \text{LOSE} \Rightarrow \text{decide the other's}

    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.

  2. CAS(w,⊥,vi);decide w\text{CAS}(w, \bot, v_i);\quad \text{decide } w

    CAS solves nn-thread consensus. A shared word starts as ⊥\bot. Each thread runs one CAS from ⊥\bot to its proposal and then decides whatever the word holds: the first CAS wins for everybody.

  3. cons⁡(register)=1,cons⁡(queue)=2,cons⁡(CAS)=∞\operatorname{cons}(\text{register}) = 1, \qquad \operatorname{cons}(\text{queue}) = 2, \qquad \operatorname{cons}(\text{CAS}) = \infty

    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.

Question 1

Thread AA's enqueue(1) completes; then thread BB's enqueue(2) starts and completes; then thread CC dequeues and gets 2. Nothing else happens. Is this history linearizable?

  1. Yes: BB's operation may take effect first
  2. No: AA's operation precedes BB's in real time, so 1 must come out first
  3. Yes, provided CC's dequeue overlaps AA's enqueue
  4. It depends on the hardware's memory model
Show the answer

B. No: AA's operation precedes BB'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.

Question 2

Why is Treiber's stack lock-free but not wait-free?

  1. Its CAS can fail spuriously, even when nobody else touched top
  2. It uses a lock internally on the top pointer
  3. A failed CAS means another operation's CAS succeeded, so the system progresses, but one thread can keep losing forever
  4. 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.

Question 3

Which fix makes Treiber's pop fail its CAS when top was changed and then changed back to the same address?

  1. Pairing top with a version counter that every successful update increments, and comparing both in one double-width CAS
  2. Retrying the CAS a second time
  3. Reading top twice before the CAS
  4. Declaring top volatile
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 T1T_1's read and its CAS the counter has moved on, so the CAS fails and T1T_1 retries. Hazard pointers solve the problem differently, by preventing the reuse itself.

Question 4

Why can no wait-free FIFO queue for two threads be built from read/write registers alone?

  1. Registers are too slow
  2. Registers cannot store pointers
  3. It can: the Michael–Scott queue uses only reads and writes
  4. 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).