top55 · end1while True:2 old = top3 node.next = old4 if cas(top, old, node):5 breakTHREAD Aold = –THREAD Bold = –8 · next ?9 · next ?5585→85→98→9
Back: shared memory (the word top and the stack of nodes)Front: the push loop and two threads, each with its new node and its oldTokens: reads of top, and compare-and-swap attempts that win or are refusedShared memory at the back: the word top, wired to a pile of node plates. In front: the push loop and two threads, each holding its new node and its private copy old. Both threads read top = 5 and link their node to 5. A's compare-and-swap flips top to 8 and node 8 joins the pile; B's, still expecting 5, is refused and changes nothing. B re-reads 8, re-links, and its compare-and-swap puts node 9 on top. The card is Python-style pseudocode: cas(top, old, node) stands for the hardware instruction. Python itself has no compare-and-swap you can use from ordinary code; the C program in the details is the real thing.

The idea

  1. A lock lets one thread in at a time. If the thread holding it is paused, say its time slice ends or it hits a page fault, every other thread must wait. A lock-free structure never makes a thread wait for another.

Two pushes race

What it buys, what it costs

What happens

;; step 1/11 · no-lock
with a lock      lock -> change -> unlock
                 holder paused  =>  everyone waits
lock-free        no lock at all
                 prepare privately, publish in ONE atomic step

delays that pause a lock holder (Michael & Scott 1996):
  scheduling preemption, page faults, cache misses

The card is Python-style pseudocode: cas(top, old, node) stands for the hardware instruction. Python itself has no compare-and-swap you can use from ordinary code; the C program in the details is the real thing. Michael and Scott call this guarantee non-blocking; most texts today say lock-free. Wait-free is stronger: every thread, not just some thread, finishes in a bounded number of steps.