了解C ++内存模型:不同运行中的不同值 [英] Understanding C++ memory model : Different values on different runs
问题描述
以下代码有什么问题?我期望看到10由consumer1和consumer2产生,但我有时看到-1。
What is wrong with the below code? I expect to see 10 to be produced by consumer1 and consumer2, but I see -1 sometimes.
#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();
}
我看到
a在consumer2 10
和
code>
a在consumer2 10
如果我理解正确, memory_order_acquire
始终与 memory_order_release
的线程同步。我错了吗?
我在x86-64位机器上运行。我用
编译g ++ file.cpp -pthread -std = c ++ 11
If I understand correctly, the thread which does memory_order_acquire
always syncs with the thread which does memory_order_release
. Am I wrong?
I am running on x86-64 bit machine. I am compiling with
g++ file.cpp -pthread -std=c++11
推荐答案
原子变量有非常漂亮的属性,读取的值是之前写过的值。而使用发布/获取语义,它甚至是写入的最后一个值。
Atomic variables have the very nice property that the value read is a value that has been written before. And with release/acquire semantics it's even the last value written.
在这种情况下,您有2次写入和两次读取。只有-1的写入被排序 - 在读取之前,10的写入不被排序。因此,任一值可以是最后写入的。它保证你读取-1或10而不是垃圾。
In this case, you have 2 writes and two reads. Only the write of -1 is sequenced-before the reads, the write of 10 is not sequenced. Therefore either value may be the last written. It's guaranteed that you read -1 or 10 and not garbage.
这篇关于了解C ++内存模型:不同运行中的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!