2. Memory Model
Memory model
C++ 11 introduced a memory model that specifies behaviour for multi-threaded programs. These rules guarantees correctness, robustness and portability for multi-threaded programs. In essence, a memory model specifies what happens when two threads access the same memory location.
If two or more threads access the same memory location and one thread wants to modify it, then there will be a data race unless
- the write is handled by an atomic operation
- the read and write happens at different times
Memory model contracts
The memory model in C++ 11 introduces varying levels of control flow order contracts available to the programmer.
What the memory model clarifies
- atomic operations- what operations can perform un-interrupted.
- partial ordering of operations- sequences of operations that must not be reordered.
- visible effects of operations- when updates on shared variables are visible to other threads.
These are- in order of optimisation possibilities and the level of expertise required:
- strong: single threading, one control flow only
- medium: multi-threading with tasks, threads, and condition variables
- weak: atomics; sequential consistency, acquire-release semantic, relaxed semantic
Roughly speaking, the stronger the contract, the less choices/options a cpp program can optimise. Conversely, the weaker the contract, the more optimisation choices a cpp program has available to optimise.
Tasks, threads and condition variables are understandable. Let's just focus on atomics.
2025-11