Search

Search papers and lessons

Compare-and-Swap

Level 2 · 11 min read

Compare-and-swap is one indivisible instruction that writes a new value only if the location still holds the value the thread last read, which lets threads update shared data without a lock.

On this page

  • Colour = topic mix
  • Systems
  • ReadReady to readNot yet

TL;DR

Compare-and-swap, usually written CAS, is a single instruction that checks a memory location and writes to it in one indivisible step. The thread names the value it expects to find. If the location still holds that value, the new value is written and the instruction reports success; if not, nothing changes and the thread tries again. This lets threads update shared data without a lock, and it is the building block of many lock-free data structures.

Builds on: Race Condition, Thread · Leads to: Wait-Free Synchronization, Linearizability

Where it's used

Standard libraries in Java and Go. Java's AtomicInteger has a compareAndSet method, and the ConcurrentLinkedQueue class, a thread-safe Queue, is built on compare-and-set on its node pointers. Go's sync/atomic package offers CompareAndSwap functions for integers and pointers. Code that counts events on many processor cores often uses these instead of a lock, because a lock makes every core wait in turn.

Operating-system kernels. An operating-system kernel must update shared state from interrupt handlers, which cannot wait for a lock. If the handler interrupted the very code that holds the lock, the handler would wait forever. A compare-and-swap never waits, so the kernel uses atomic compare-and-exchange operations for counters and list pointers.

Databases and cloud key-value stores. Many stores support conditional writes: "write this record only if its version is still 7". Amazon DynamoDB, for example, lets a write carry a condition that makes it fail when the item has changed. This is the same idea as CAS, applied to a stored record instead of a processor word.

How it works

Take one shared counter, cc, that holds 5, and two threads, A and B, that each want to add 1 to it. A Thread that uses CAS does not hold a lock. It reads the counter, computes the new value, and then asks the hardware to write it only if the counter has not changed since the read. Recall that a race happens when two threads read the same value and then both write, so one write overwrites the other. CAS turns that second write into a test that can fail.

  1. Both threads read. A reads the counter and gets 5. B reads the counter and also gets 5. Check: both threads remember the expected value 5.
  2. A attempts its write. A asks for "write 6 if the counter holds 5". The counter holds 5, so the test passes, the counter becomes 6, and the instruction reports success. Check: the counter is 6.
  3. B attempts its write. B asks for "write 6 if the counter holds 5". The counter now holds 6, so the test fails. The counter stays 6, and the instruction reports failure. Check: B's write did not overwrite A's work.
  4. B retries. B reads again and gets 6, computes 7, and asks for "write 7 if the counter holds 6". The test passes. Check: the counter is 7, which is the correct total for two increments.
sequenceDiagram
  participant A as Thread A
  participant C as Counter
  participant B as Thread B
  A->>C: read (gets 5)
  B->>C: read (gets 5)
  A->>C: CAS expect 5 write 6 (succeeds)
  B->>C: CAS expect 5 write 6 (fails)
  B->>C: read (gets 6)
  B->>C: CAS expect 6 write 7 (succeeds)
  Note over C: Final value 7

Every thread that uses CAS for an update follows the same pattern, which is a retry loop. The loop reads, computes, and tries to write, and it stops only when the write succeeds:

repeat:
    e = read the counter
    v = e + 1
    try to write v only if the counter still equals e
    if the write succeeded, stop; otherwise repeat

Notice what the loop never does: it never waits for another thread. A thread that loses simply does more work and tries again, and at least one thread always succeeds in each round.

The math

Definition: Compare-and-swap
For a shared location cc, an expected value ee and a new value vv, the operation CAS(c,e,v)\mathrm{CAS}(c, e, v) does this: if c=ec = e, it sets cc to vv and returns true; otherwise it leaves cc unchanged and returns false. The comparison and the write happen as one indivisible step, so no other thread can change cc between them.

Step 2 in symbols: the first write succeeds

Both threads read c0=5c_0 = 5, so both have the expected value eA=eB=5e_A = e_B = 5. A's call is CAS(c,5,6)\mathrm{CAS}(c, 5, 6). The test is c0=5=eAc_0 = 5 = e_A, which is true, so the location becomes c1=6c_1 = 6 and the operation returns true.

Step 3 in symbols: the second write fails

B's call is also CAS(c,5,6)\mathrm{CAS}(c, 5, 6), but the location is now c1=6c_1 = 6. The test is c1=6≠5=eBc_1 = 6 \neq 5 = e_B, which is false. The location stays at c1=6c_1 = 6 and the operation returns false.

Step 4 in symbols: the retry succeeds

B reads again and gets eB′=c1=6e'_B = c_1 = 6, so it computes v=6+1=7v = 6 + 1 = 7 and calls CAS(c,6,7)\mathrm{CAS}(c, 6, 7). The test c1=6=eB′c_1 = 6 = e'_B holds, so c2=7c_2 = 7.

In general, if ctc_t is the value after tt successful operations, each successful increment sets ct+1=ct+1c_{t+1} = c_t + 1. Failed attempts do not change the counter at all.

A useful fact follows from the test. Suppose nn threads all read the same value ee and each calls CAS(c,e,e+1)\mathrm{CAS}(c, e, e + 1), one after another. The first call passes and sets c=e+1c = e + 1. Every later call tests e+1=ee + 1 = e, which is false. So exactly one of the nn calls succeeds, and n−1n - 1 threads must read again.

Worked examples

Example
1. One success, one rejected write (tiny)

The counter cc starts at 0. Thread A calls CAS(c,0,1)\mathrm{CAS}(c, 0, 1), and then thread B calls CAS(c,0,5)\mathrm{CAS}(c, 0, 5) with the value 0 it read earlier.

  1. A's call tests c=0c = 0. The counter holds 0, so the test passes. The counter becomes 1 and the call returns true.
  2. B's call tests c=0c = 0. The counter holds 1, so the test fails. The counter stays at 1 and the call returns false.
  3. B's write of 5 was never applied, so the counter is 1.

Interpretation: B's expected value was out of date. The rejected write is the mechanism that protects the counter from a stale update.

Example
2. Four threads, one winner per round (standard)

Four threads each read the counter, which holds 5, and each tries to add 1 with CAS. Assume that the losers of each round all read again before the next round starts.

  1. Round 1: four calls to CAS(c,5,6)\mathrm{CAS}(c, 5, 6). The first succeeds, so c=6c = 6. Three calls fail.
  2. Round 2: the three losers read 6 and call CAS(c,6,7)\mathrm{CAS}(c, 6, 7). One succeeds, so c=7c = 7. Two calls fail.
  3. Round 3: the two losers read 7 and call CAS(c,7,8)\mathrm{CAS}(c, 7, 8). One succeeds, so c=8c = 8. One call fails.
  4. Round 4: the last loser reads 8 and calls CAS(c,8,9)\mathrm{CAS}(c, 8, 9). It succeeds, so c=9c = 9.
  5. Count the calls. There are 4+3+2+1=104 + 3 + 2 + 1 = 10 calls in total. Four succeed and 10−4=610 - 4 = 6 fail.

Interpretation: four increments give 9, which is correct. The price of the lock-free approach is the six wasted calls. With more threads and more contention, the wasted work grows.

Example
3. Deposit and withdrawal on one balance (realistic)

A bank balance holds 100 dollars. Thread W withdraws 30 dollars and thread D deposits 50 dollars. Both read 100 first. The update in each thread is to read the balance, compute the new balance, and write it with CAS.

  1. D calls CAS(balance,100,150)\mathrm{CAS}(\text{balance}, 100, 150). The balance is 100, so the write goes through and the balance is 150.
  2. W calls CAS(balance,100,70)\mathrm{CAS}(\text{balance}, 100, 70). The balance is now 150, not 100, so the call fails and nothing is written.
  3. W reads again and gets 150. It computes 150−30=120150 - 30 = 120.
  4. W calls CAS(balance,150,120)\mathrm{CAS}(\text{balance}, 150, 120). The balance is 150, so the call succeeds and the balance is 120.
  5. Check: 100+50−30=120100 + 50 - 30 = 120, which is the correct final balance.

Interpretation: a plain store would have written 70 in step 2 and erased the deposit. CAS made the withdrawal notice the deposit and redo its arithmetic from the new value.

Try it: the balance is 100. Thread A deposits 20 dollars and thread B withdraws 50 dollars, and both read 100. A's CAS succeeds first, so the balance becomes 120. B's CAS fails, B reads 120 and computes 70, and its second CAS succeeds. What is the final balance? Answer: 70, because 100+20−50=70100 + 20 - 50 = 70.

Common mistakes and tradeoffs

It is tempting to think CAS makes a whole update atomic; in fact it makes one location atomic. The instruction compares and writes a single word. An update that changes two fields, such as moving an item from one list to another, needs more than one CAS, and another thread can run between them. Such updates usually need a lock or a design where the whole record is replaced by one CAS on a pointer to it.

It is tempting to think a successful CAS means nothing changed since the read; in fact only the value matches. If the value goes from A to B and back to A, a CAS expecting A succeeds even though the data changed. This is the ABA problem. For example, a stack has a top node X, and each node stores a Pointer to the next one. Thread T reads the top as X and its next node as Y, then stalls. Other threads pop X, pop Y, and push a node back at the same address as X. T's CAS that expects X and writes Y succeeds, and the stack now points to Y, which was already removed. The usual fixes are a version counter stored next to the pointer, so that a changed history never looks the same, or special memory-reclamation schemes such as hazard pointers.

It is tempting to think lock-free means fast; in fact a retry loop wastes work under contention. When many threads hit the same location, most calls fail, as Example 2 showed. A CAS-based design is lock-free, meaning that some thread always makes progress, but it is not automatically wait-free, meaning that a particular thread may keep losing and never finish. Wait-Free Synchronization is the stronger guarantee.

When to use it. Use CAS for counters, flags and single pointers, where one word captures the whole state. When not to use it. Avoid it when an invariant spans several fields, or when the update is expensive enough that many failed retries would waste more time than a lock. Alternatives. A lock is simpler and safer for multi-step updates. Message passing lets one thread own the data. Replacing a whole immutable record with one CAS on its pointer never leaves a half-updated value visible, although the ABA issue still applies when addresses are reused.

History

Before the 1970s, programmers protected shared data with interrupt masking or with software locks built from plain reads and writes. IBM's System/370 line, introduced in 1970, included a compare-and-swap instruction so that programs could update shared data without first disabling interrupts. For years it was mostly a tool for operating-system and database programmers.

Interest in lock-free programming grew as multiprocessor machines became common. A thread that holds a lock can be paused by the operating system, and every other thread then waits. In 1991 Maurice Herlihy showed that CAS can let any number of threads agree on a value without waiting, while simpler primitives such as plain reads and writes cannot do this for more than two threads. That result is one reason CAS became the standard building block for lock-free designs.

Recap

  • A race happens when two threads read shared data and then write, so one write overwrites the other's update.
  • CAS checks that a location still holds the expected value and writes the new value in one indivisible step.
  • A failed CAS means another thread changed the value first; the thread reads again and retries.
  • The retry loop never waits, so some thread always succeeds, but a given thread can keep losing.
  • Watch for the ABA problem and for updates that touch more than one location.

Next, read Wait-Free Synchronization to see the strongest progress guarantee, and Linearizability for the correctness rule these objects must meet.

Check yourself

QuestionWhat three inputs does compare-and-swap take, and what does it do with them?Show answer
It takes a location, an expected value and a new value. If the location holds the expected value, it writes the new value and reports success; otherwise it changes nothing and reports failure.
QuestionA counter holds 10. Thread A calls CAS(c, 10, 11) and succeeds. Thread B then calls CAS(c, 10, 11). What does B get, what is the counter, and what should B do next?Show answer
B's call fails because the counter holds 11, not 10. The counter stays at 11. B should read again, getting 11, and then call CAS(c, 11, 12), which succeeds and leaves the counter at 12.
QuestionWhy does CAS not need a lock to protect the check and the write?Show answer
The comparison and the write are one indivisible step, so no other thread can change the location between the check and the write. A thread that loses does not wait; it reads the new value and retries.
QuestionFive threads each read a counter holding 0 and each call CAS(c, 0, 1) at the same time. How many calls succeed, and what is the counter afterwards?Show answer
Exactly one call succeeds, because the first write changes the counter to 1 and every later call tests against 0. The counter is 1, and the other four threads must read again.

Sources