当我运行这个程序时,我得到的输出为 10,这对我来说似乎是不可能的。我在 x86_64 core i3 ubuntu 上运行它。
如果输出为 10,则 1 必须来自 c 或 d。
同样在线程 t[0] 中,我们将 c 赋值为 1。现在 a 为 1,因为它出现在 c=1 之前。c 等于 b,线程 1 将其设置为 1。所以当我们存储 d 时,它应该是 1,因为 a=1。
- memory_order_seq_cst 可以输出 10 吗?我尝试在第一行(变量 =1 )和第二行(printf)之间的两个线程上插入 atomic_thread_fence(seq_cst) 但它仍然不起作用。
取消注释两个栅栏都不起作用。尝试使用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