Interleavings of a Shared Counter

A counter increment may consist of a read, computation, and write. Interleaving those steps risks losing an intended update under an uncoordinated model.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a schematic schedule
  2. Use the language's actual coordination model
  3. List reads and writes as separate actions
  4. Use a test schedule that forces the interaction

Trace a schematic schedule

Both workers read ten before either writes. Both calculate eleven, then both store it. This illustrates the same lost-update pattern as separate database reads and writes.

Use the language's actual coordination model

Unsynchronized access may have stronger consequences than that illustrative schedule in some languages. Choose an atomic or synchronized update allowed by the runtime. See shared worker state.[1]

List reads and writes as separate actions

Two workers each want to add one to a counter initialized at five. If both load five before either stores, both compute six and the final value is six. Merely observing that individual reads and writes are available does not make a compound increment atomic. See lost database updates.

A reads 5
B reads 5
A writes 6
B writes 6
Correct cumulative increment would end at 7

Use a test schedule that forces the interaction

An atomic increment or protecting the entire read–modify–write sequence can preserve both updates under the chosen memory and synchronization model. Construct a controlled overlap with synchronization points that establish the order.

References

  1. OpenMP Architecture Review Board, OpenMP API Specifications ↩