What is wrong with the code below? I expect 10 to be produced by consumers1 and consumer2, but sometimes I see -1.
#include <thread>
#include <atomic>
#include <cassert>
#include <string>
std::atomic<int> global;
void producer()
{
global.store(10, std::memory_order_release);
}
void consumer1()
{
int a = global.load(std::memory_order_acquire);
printf("a in consumer1 %d\n", a);
}
void consumer2()
{
int a = global.load(std::memory_order_acquire);
printf("a in consumer2 %d\n", a);
}
int main()
{
global.store(-1, std::memory_order_seq_cst);
std::thread t1(producer);
std::thread t2(consumer1);
std::thread t3(consumer2);
t1.join(); t2.join(); t3.join();
}
I see a in consumer1 10
a in consumer2 10
as well a in consumer1 -1
a in consumer2 10
If I understand correctly, the thread that executes memory_order_acquire
is always synchronized with the thread that does memory_order_release
. Am I mistaken? I am running on an x86-64 bit machine. I am compiling with g ++ file.cpp -pthread -std = C ++ 11
source
share