C++ memory model
- C++ course
- Expert
- Lesson 13/47
- 5 min
Learn the C++ memory model and atomic basics.
C++ memory model
The C++ memory model defines how threads access memory and under what conditions they observe consistent results. The standard library's std::atomic<T> template ensures each access is indivisible (atomic).
Example: std::atomic<int> counter{0};. Here counter.store(5) writes and counter.load() reads. Even if two threads access it concurrently, no race occurs; the value stays consistent. This is the cornerstone of multithreaded programs.
Atomic access
Each thread has its own view of memory; without synchronization, a thread may not see what another wrote. std::atomic solves this: every read and write is indivisible.
Example: one thread does counter.store(7), another calls counter.load(). Thanks to atomic access, the load sees either the old value 0 or the new value 7; it never reads a half-written value. fetch_add does read-modify-write as one indivisible step.
Practice Use the atomic counter
Define a global std::atomic<int> counter{0};. In main write counter.store(7); and std::cout << counter.load();.
Starter code
#include <iostream>
#include <atomic>
// Define the atomic counter variable here
int main() {
// Store a value and print it
return 0;
}Sample solution
#include <iostream>
#include <atomic>
std::atomic<int> counter{0};
int main() {
counter.store(7);
std::cout << counter.load();
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the C++ memory model define?
std::atomic<int> counter{0};- Only variable sizes
- Multithreaded memory access Correct answer
- Compiler versions
- Class member ordering
Explanation: The memory model defines how threads access memory and what counts as consistent.
2 Complete the atomic variable
std::atomic<int> ____; // ready flag
std::atomic<int> ready; // ready flag
Explanation: The ready atomic flag is declared this way.
3 Match each piece to its role
| Term | Meaning |
|---|---|
std::atomic<int> |
Atomic access |
thread T(func) |
Thread start |
x.store(5) |
Atomic write |
x.load() |
Atomic read |