The idea
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.
Our example is a stack of linked nodes. The shared word top says which node is first; each node points to the next. Now it holds node 5. To push, link the new node to the old top, then point top at it.
The tool is compare-and-swap (CAS), one atomic instruction: if top still holds what I read, replace it with my node and report success; otherwise change nothing and report failure. No other thread can act in the middle.
Two pushes race
Thread A wants to push node 8 and thread B node 9, at the same moment. Both run line 2 and read top. Both see node 5 and keep it in their own variable old.
Line 3: each thread points its new node at node 5. These nodes are still private, so nothing shared has changed yet. Any number of threads can do this at once.
Thread A runs cas(top, 5, 8). Top still holds 5, so in one atomic step top becomes 8: node 8 is now on the stack. The CAS reports success and A leaves the loop.
Thread B runs cas(top, 5, 9). But top now holds 8, not 5, so the CAS changes nothing and reports failure. A plain top = node here would have thrown node 8 away.
The loop sends B back to line 2. It reads top again and gets 8, then points node 9 at node 8. It lost nothing but a few instructions, and it never waited for A.
Now cas(top, 8, 9) finds 8 in top, so top becomes 9. The stack reads 9, 8, 5: both pushes kept, in some order, and no lock was ever taken.
What it buys, what it costs
B's CAS failed only because A's succeeded. A failed (strong) CAS always means another thread made progress, so the stack as a whole never stalls, even if a thread is paused mid-push. That guarantee is called lock-free.
CAS checks only the value. If top goes from node X to Y and back to X between a read and a CAS, the CAS wrongly succeeds; with pops and reused nodes, that breaks the list. Fixes: a change counter beside top, or delayed freeing.
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.