liveBook · Manning

Invariant

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

An invariant is a condition that remains true about a data structure or program state when it is in a valid state.

An invariant is a condition that remains true about a data structure in a valid state. Updates may temporarily break it; shared access becomes risky if another thread can observe that intermediate state. section 3.1

Removing a node from a doubly linked list

If node A points next to B, B should point back to A. Removing a node requires changing both neighboring links. Between those updates, the forward and backward links disagree, so a concurrent reader may observe a broken invariant. section 3.1

Figure 3.1. Deleting a node from a doubly linked list

The diagram shows how deleting a node temporarily leaves the links inconsistent. section 3.1

Ways to prevent other threads from observing broken invariants include:

  • Protect the data structure so other threads cannot see intermediate updates. section 3.1.2
  • Redesign updates as indivisible changes that each preserve the invariants; this is difficult and involves memory-model nuances. section 3.1.2
  • Use transactional updates that commit together and restart if another thread has changed the data. section 3.1.2

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

How deep it goes
Works through a doubly linked-list deletion and explains how separate updates temporarily break its invariant.
Examples
Uses doubly linked-list deletion and queue insertion to illustrate broken and preserved invariants.
What you can do after
Evaluate whether concurrent updates can expose a data structure while its invariants are broken.
How it connects
Connects invariants to race conditions, mutexes, lock-free programming, and software transactional memory.

Also explained in

Compare how 12 books explain invariant →

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.