liveBook · Manning

Read-modify-write operation

As explained in C++ Concurrency in Action, Second Edition

A read-modify-write operation atomically reads a value, modifies it, and writes the result as one operation.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains return values, compare-exchange failures, release sequences, and cache contention through concrete C++ cases.
Examples
Uses atomic booleans, pointer arithmetic, a reference-counted lock-free stack, and a contended atomic counter.
What you can do after
Evaluate atomic updates by tracing their values, synchronization effects, and possible contention costs.
How it connects
Connects atomic operations to compare-exchange, memory ordering, release sequences, synchronizes-with relationships, and lock-free data structures.

Also explained in

Compare how 3 books explain read-modify-write operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.