Multicore & Synchronization
What does the atomic CAS (compare-and-swap) instruction do?
- AIt writes a new value only if memory equals an expected value, and reports whether it succeeded
- BIt compares two memory values and writes the larger into both
- CIt swaps a memory value and a register value unconditionally
Show answer and explanation
Answer: A. It writes a new value only if memory equals an expected value, and reports whether it succeeded
CAS atomically performs "if the value at this address is still the expected value, change it to the new value". If another thread changed the value between the read and the write, it fails, so updates proceed only when nothing has interfered. Wrapping it in a loop that rereads, recomputes and retries on failure lets shared values be updated safely without a lock. x86's cmpxchg instruction is an example.
- A. Correct. Compare, and swap if equal.
- B. It does not write the larger value.
- C. An unconditional swap is the exchange instruction.