← Lessons

quiz vs the machine

Platinum1720

Concurrency

The Lock Free Stack Treiber

The classic compare and swap stack and the subtle reuse hazard it exposes.

5 min read · advanced · beat Platinum to climb

A single atomic top

The Treiber stack is the textbook lock free stack. It keeps one atomic pointer to the top node. Both push and pop are loops that read the current top, prepare a change, and commit it with a single compare and swap, retrying when another thread wins the race.

Push and pop

  • Push creates a new node, sets its next field to the current top, then compare and swaps top from the old value to the new node
  • Pop reads the current top, reads its next field, then compare and swaps top from the old node to that next node, returning the old node's value

Because each operation commits with one atomic instruction, the stack never blocks and a stalled thread cannot stop others from progressing.

The reuse hazard

The pop path hides a famous trap. A thread reads top as node A and plans to swap to A's old next. If between those steps A is popped, freed, and a recycled allocation makes top point at A again, the compare and swap sees the expected A and succeeds wrongly, corrupting the stack. This is the reuse problem that motivates tagged pointers or hazard pointers.

Key idea

The Treiber stack pushes and pops with a single compare and swap on the top pointer, but its pop path is vulnerable to the reuse hazard.

Check yourself

Answer to earn rating on the learn ladder.

1. How does the Treiber stack commit a push or pop?

2. What is the reuse hazard in pop?

3. What guards against the reuse hazard?