Summary - Memory model
- C++ course
- Expert
- Lesson 18/47
- 5 min
Combine memory model, happens-before and acquire-release to write a sync primitive.
Summary - Memory model
In this group you saw the core tools of the memory model: std::atomic, happens-before, sequential consistency, data race and acquire-release. All ensure correctness of multithreaded programs.
Now you will combine them in an atomic counter example. store, fetch_add and load will all appear in one program; you will see how atomic access fits together.
Atomic counter
An std::atomic<int> counter gets an initial value with store, is incremented indivisibly with fetch_add, and is read with load. All operations are atomic, so no data race occurs.
Example: counter.store(5); counter.fetch_add(3); std::cout << counter.load();. The result is 8. Here fetch_add uses the default seq_cst ordering; even in a single thread the behavior is deterministic.
Practice Combine the atomic counter
Define a global std::atomic<int> counter{0};. In main write counter.store(5);, counter.fetch_add(3); and std::cout << counter.load();.
Starter code
#include <iostream>
#include <atomic>
// Define the atomic counter here
int main() {
// Initialize counter, increment and print
return 0;
}Sample solution
#include <iostream>
#include <atomic>
std::atomic<int> counter{0};
int main() {
counter.store(5);
counter.fetch_add(3);
std::cout << counter.load();
return 0;
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the default memory order for std::atomic operations?
x.store(5); // default- memory_order_relaxed
- memory_order_seq_cst Correct answer
- memory_order_release
- memory_order_acquire
Explanation: seq_cst is the default ordering; it gives the strongest guarantee.
2 Complete the fetch_add ordering
counter.fetch_add(1, std::memory_order_____);
counter.fetch_add(1, std::memory_order_relaxed);
Explanation: relaxed provides only atomicity; if no ordering is needed it suffices.
3 Match each tool to its trait
| Term | Meaning |
|---|---|
std::atomic |
Indivisible access |
happens-before |
Cross-thread order |
seq_cst |
Total order, default |
acquire-release |
Paired ordering |