Multicore & Synchronization

What does a fetch-and-add instruction, such as RISC-V amoadd.w or x86 lock xadd, do?

  1. AIt only reads memory and does the addition in a register
  2. BIt adds the values at two memory addresses and writes the sum to a third
  3. CIt atomically adds a given number to a memory value and returns the value before the addition
Show answer and explanation

Answer: C. It atomically adds a given number to a memory value and returns the value before the addition

Fetch-and-add performs the read, add and write as one atomic operation, so a single instruction fixes the counter++ data race. Because it returns the value before the addition, it can also hand out tickets in order, such as assigning each thread a unique number. With no failure and retry, unlike a CAS loop, it performs better when many threads update at once.

  • A. The add and the memory write are both done atomically.
  • B. It is not a memory-to-memory operation.
  • C. Correct. It suits shared counters.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Which describes a spinlock?
  2. In which situation is a spinlock least suitable?
  3. Why does a spinlock usually wait with ordinary reads and use an atomic instruction only when the lock looks free (test-and-test-and-set), instead of retrying the atomic write directly?
  4. Which correctly compares a mutex (a lock that sleeps while waiting) with a spinlock?
  5. Which is an example of deadlock?