Multicore & Synchronization
What does a fetch-and-add instruction, such as RISC-V amoadd.w or x86 lock xadd, do?
- AIt only reads memory and does the addition in a register
- BIt adds the values at two memory addresses and writes the sum to a third
- 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.