当我运行这个程序时,输出为10,这对我来说似乎是不可能的。我是在x86_64核心i3 ubuntu上运行这个的。
如果输出为10,那么1必须来自c或d。
同样在线程t中,我们将c赋值为1。现在a是1,因为它发生在c=1之前。c等于b,被线程1设置为1。所以当我们存储d时,它应该是1作为a=1。
取消对两个fence的注释都不起作用。尝试使用g++和clang++运行。两者都给出了相同的结果。
#include<thread>
#include<unistd.h>
#include<cstdio>
#include<atomic>
using namespace std;
atomic<int> a,b,c,d;
void foo(){
a.store(1,memory_order_seq_cst);
// atomic_thread_fence(memory_order_seq_cst);
c.store(b,memory_order_seq_cst);
}
void bar(){
b.store(1,memory_order_seq_cst);
// atomic_thread_fence(memory_order_seq_cst);
d.store(a,memory_order_seq_cst);
}
int main(){
thread t[2];
t[0]=thread(foo); t[1]=thread(bar);
t[0].join();t[1].join();
printf("%d%d\n",c.load(memory_order_seq_cst),d.load(memory_order_seq_cst));
}bash$ while [ true ]; do ./a.out | grep "10" ; done
10
10
10
10发布于 2021-03-28 10:15:46
printf语句是不同步的,因此10的输出可以只是一个重新排序的01。
01发生在printf之前的函数连续运行时。
https://stackoverflow.com/questions/66840161
复制相似问题