A read-modify-write operation atomically reads an atomic value, changes it, and stores the result. Unlike a separate load followed by a store, the update is one operation; functions such as exchange() and fetch_add() can also return the previous value. section 5.2.3 section 5.2.4
Common forms include:
- exchange() replaces the stored value and returns its original value. section 5.2.3
- fetch_add() and fetch_sub() update an atomic pointer by an offset and return the prior pointer; function forms can specify memory ordering. section 5.2.4
- Compare-exchange stores a desired value when the current value matches an expected value. On failure, it updates expected; weak compare-exchange can also fail spuriously. section 5.2.3
std::atomic<bool> b; bool x=b.load(std::memory_order_acquire); b.store(true); x=b.exchange(false,std::memory_order_acq_rel);
The exchange call replaces the atomic value with false and assigns the previous value to x. section 5.2.3
Read-modify-write operations can form part of a release sequence, allowing a later atomic read to synchronize with an earlier write when the memory-order requirements are met. They also have performance costs under contention: competing processors may pass the updated cache line back and forth, even with relaxed ordering. section 5.3.1 section 8.2.2


