liveBook · Manning

Read-modify-write operation

As explained in Modern C

A read-modify-write operation atomically reads an object, computes or applies a modification, and writes the resulting value as one indivisible operation.

A read-modify-write operation reads an atomic object, applies a modification, and writes the result as one indivisible operation. Unlike a separate load followed by a store, it can synchronize on its read side with one thread and on its write side with others. section 19.1

C identifies several atomic operations as read-modify-write operations:

  • atomic_exchange and atomic_compare_exchange_weak for _Atomic objects. section 19.1
  • Compound assignments and equivalent interfaces, including increment and decrement operators for arithmetic _Atomic objects. section 19.1
  • atomic_flag_test_and_set for atomic_flag. section 19.1

Selecting acquire-release semantics

An atomic counter can be incremented with atomic_fetch_add_explicit, passing memory_order_acq_rel as its consistency model. The explicit interface makes the synchronization choice visible instead of relying on the default sequentially consistent form. section 19.4

   _Atomic(unsigned) at = 67;
   ...
   if (atomic_fetch_add_explicit(&at, 1, memory_order_acq_rel)) {
     ...
   }


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":10}],[{\"line\":0,\"ch\":11},{\"line\":0,\"ch\":19}],[{\"line\":2,\"ch\":3},{\"line\":2,\"ch\":5}],[{\"line\":2,\"ch\":7},{\"line\":2,\"ch\":32}],[{\"line\":2,\"ch\":41},{\"line\":2,\"ch\":61}]]"}
!@%STYLE%@!

Inspect the complete counter fragment: it declares an atomic unsigned object and applies atomic_fetch_add_explicit with memory_order_acq_rel. section 19.4

How Modern C covers it

How deep it goes
Distinguishes operation categories and explains explicit memory-order choices, but does not develop their platform-level implementation.
Examples
Uses atomic_fetch_add_explicit on an atomic counter and lists exchange, compare-exchange, compound assignment, increment, decrement, and atomic-flag forms.
What it assumes
Assumes atomic objects, multiple threads, and basic distinctions between reading, writing, and synchronization operations.
What you can do after
Apply it via atomic_fetch_add_explicit or compare-exchange interfaces with an explicitly selected memory_order value.
How it connects
Connects atomic objects with acquire-release consistency, sequential consistency, relaxed consistency, and the happened-before relation.

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 Modern C. The section links point to the parts of the book it draws on.