Multicore & Synchronization

The code above doubles the shared variable counter using CAS(&p, expected, new). When does the CAS fail so the loop repeats?

int old, new;
do {
    old = counter;
    new = old * 2;
} while (!CAS(&counter, old, new));
  1. AWhen counter is 0
  2. BWhen another thread changes counter between reading old and executing the CAS
  3. CWhen new is larger than old
Show answer and explanation

Answer: B. When another thread changes counter between reading old and executing the CAS

CAS writes the new value only if counter still equals the old value read earlier. If another thread changed it meanwhile, the local new was computed from a stale value, so CAS does not write it and reports failure. The loop rereads the latest value and recomputes. A plain addition could use fetch-and-add, but this pattern makes any update, such as doubling, atomic.

  • A. Even with 0 it succeeds if no one else changed it.
  • B. Correct. It discards the computation based on the old value and retries.
  • C. Relative size is not the failure condition.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. With an instruction pair such as RISC-V LR/SC (load-reserved / store-conditional), when does the SC fail?
  2. Which describes the ABA problem that affects lock-free data structures built with CAS?
  3. What does a fetch-and-add instruction, such as RISC-V amoadd.w or x86 lock xadd, do?
  4. Which describes a spinlock?
  5. In which situation is a spinlock least suitable?