Multicore & Synchronization

int old, new;
do {
    old = counter;
    new = old * 2;
} while (!CAS(&counter, old, new));

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

  1. AWhen counter is 0
  2. BWhen another thread changes counter between reading old and executing the CAS, so that it no longer equals old
  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, so that it no longer equals old

CAS writes the new value only if counter still equals the old value read earlier. If another thread changed it meanwhile so that counter no longer equals old, 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. Being 0 does not matter; it succeeds if counter still equals old.
  • B. Correct. It discards the computation based on the old value and retries.
  • C. Relative size is not the failure condition.