i tested this code a lot and its assertion was never failed
but can its assertion fail sometimes ?
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <cassert>
std::atomic<bool> x{false};
std::atomic<int> y{0};
void write_x() {
x.store(true, std::memory_order_release);
}
void write_y() {
y.store(1, std::memory_order_relaxed);
}
void read_x_then_y() {
while (!x.load(std::memory_order_acquire));
std::this_thread::sleep_for(std::chrono::seconds(1)); // allow write_y thread to store 1 in to y befor reading it
assert(y.load(std::memory_order_relaxed) == 1); // could this assert fail ?
}
int main() {
std::thread t1{read_x_then_y};
std::thread t2{write_x};
std::thread t3{write_y};
t1.join();
t2.join();
t3.join();
}
there is no memory operation before release store in write_x function
so the acquire load in read_x_then_y should never see the store operation happened in write_y function
is it right ?