Multicore & Synchronization

What does the atomic CAS (compare-and-swap) instruction do?

  1. AIt writes a new value only if memory equals an expected value, and reports whether it succeeded
  2. BIt compares two memory values and writes the larger into both
  3. 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.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. The code above doubles the shared variable counter using CAS(&p, expected, new). When does the CAS fail so the loop repeats?
  2. With an instruction pair such as RISC-V LR/SC (load-reserved / store-conditional), when does the SC fail?
  3. Which describes the ABA problem that affects lock-free data structures built with CAS?
  4. What does a fetch-and-add instruction, such as RISC-V amoadd.w or x86 lock xadd, do?
  5. Which describes a spinlock?