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));
- AWhen counter is 0
- BWhen another thread changes counter between reading old and executing the CAS
- 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.