Search⌘ K

CppMem: Atomics with a Relaxed Semantic

Learn to analyze relaxed atomic operations in C++ concurrency with CppMem. Understand how atomicity is guaranteed without synchronization or ordering, and explore the impact on thread interleaving and possible variable values through practical examples and graph visualizations.

We'll cover the following...

With the relaxed semantic, we don’t have synchronization or ordering constraints on atomic operations; only the atomicity of the operations is guaranteed.

C++
// ongoingOptimisationRelaxedSemantic.cpp
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> x{0};
std::atomic<int> y{0};
void writing(){
x.store(2000, std::memory_order_relaxed);
y.store(11, std::memory_order_relaxed);
}
void reading(){
std::cout << y.load(std::memory_order_relaxed) << " ";
std::cout << x.load(std::memory_order_relaxed) << std::endl;
}
int main(){
std::thread thread1(writing);
std::thread thread2(reading);
thread1.join();
thread2.join();
};

For the relaxed semantic, my key questions are very easy to answer. These are my questions:

  1. Does the program have well-defined behavior?
  2. Which values for x and y are possible?

On one hand, all operations on x and y are atomic, so the program is well-defined. On the other hand, there are no restrictions on the possible ...