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 so that it no longer equals the expected value, it fails. Only the value is compared, so a value that changed and then returned still succeeds (the ABA problem). 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 with the lock prefix 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.