memory_order
- C++ course
- Advanced
- Lesson 26/83
- 5 min
Learn memory ordering with memory_order.
memory_order
memory_order sets the visibility and ordering guarantees of an atomic operation. The default std::memory_order_seq_cst is the strongest; all threads see the same order. Weaker orderings trade safety for speed but need care.
std::memory_order_relaxed guarantees only atomicity; no ordering. std::memory_order_acquire sees prior writes when reading; std::memory_order_release publishes changes made before writing. These two form producer-consumer synchronization. Beginners should use seq_cst.
acquire and release
When one thread does store(v, std::memory_order_release) and another reads with load(std::memory_order_acquire), the reader sees all changes the writer made before the release. This sets up producer-consumer synchronization.
Example: the producer prepares data, then ready.store(true, release). The consumer ready.load(acquire) sees true and knows the data is ready. This pair is the foundation of lock-free synchronization. Wrong ordering can introduce data races; use it carefully.
Practice store/load with relaxed
Create std::atomic<int> a{0};. Write with a.store(1, std::memory_order_relaxed); and read with std::cout << a.load(std::memory_order_relaxed);. Include the <atomic> header.
Starter code
#include <iostream>
#include <atomic>
int main() {
// Create an atomic, store/load with relaxed
return 0;
}Sample solution
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> a{0};
a.store(1, std::memory_order_relaxed);
std::cout << a.load(std::memory_order_relaxed);
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the memory_order constant
std::atomic<int> a{0};
a.store(1, std::____);
std::atomic<int> a{0};
a.store(1, std::memory_order_relaxed);
Explanation: memory_order_relaxed guarantees only atomicity.
2 What does memory_order_relaxed NOT guarantee?
- Atomicity
- Operation ordering Correct answer
- Type safety
- Memory size
Explanation: relaxed guarantees only atomicity; it has no ordering.
3 Match each ordering to its purpose
| Term | Meaning |
|---|---|
memory_order_relaxed |
Atomicity only |
memory_order_acquire |
See on read |
memory_order_release |
Publish on write |
memory_order_seq_cst |
Strongest guarantee |