Skip to content
BytePatterns

Compare-and-Swap

Concurrency: lesson 15 of 15

Publish the new value only if nobody changed the old one.

Lesson 15 of 15 · 5 min

Compare-and-Swap

Step 1 of 9

One shared cell holding ten, and two threads that both want to change it. No lock anywhere.

The Idea

Compare-and-swap takes an address, the value you expect there, and the value you want. The hardware writes only if the expectation still holds, and tells you which happened. A failed swap is not an error — it is news, and the answer is to re-read and try again.

Real-World Example

Editing a shared document by saving with "only if nobody else saved since I opened it". If someone did, your save is refused, you reload their version and reapply your change rather than flattening it.

The Code

class Cell:
    def __init__(self, v): self.v = v
    def cas(self, expect, new):
        if self.v != expect: return False      # somebody moved it
        self.v = new; return True

cell, tries, meddle = Cell(10), 0, [True, False]
while True:
    tries += 1
    seen = cell.v                              # read
    if meddle.pop(0): cell.v += 5              # another thread wins the race
    if cell.cas(seen, seen + 1): break         # compute, then publish or retry
print(tries, cell.v)                           # 2 16

Python

Your turn

What does this print?

class Cell:
  def __init__(self, v): self.v = v
  def cas(self, expect, new):
      if self.v != expect: return False
      self.v = new; return True

c = Cell(4)
print(c.cas(4, 9), c.cas(4, 11), c.v)

Mini quiz

1 / 3

A compare-and-swap fails when:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.