Search⌘ K

CppMem: Atomics with Non-Atomics

Understand the correct use of acquire-release semantics in C++ concurrency and why non-atomic variables can cause data races. Learn to identify and analyze these issues using CppMem, enhancing your ability to optimize concurrent programs safely.

We'll cover the following...

A typical misunderstanding in the application of the acquire-release semantic is to assume that the acquire operation is waiting for the release operation. Based on this wrong assumption, you may think that x does not have to be an atomic variable and we can further optimize the program.

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

The program has a data ...