Understanding C ++ memory model: different values ​​for different runs

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_acquireis 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

+4
source share
2 answers

, , . / .

2 . -1 - 10 . . , -1 10, .

+4

global.store(10, std::memory_order_release);

-1.

, std:: memory_order , sempaphore, . . cppreference

+3

Source: https://habr.com/ru/post/1610691/


All Articles