【发布时间】:2017-02-23 11:47:57
【问题描述】:
在下面的代码中,线程 2 中 x 的值将始终为 10,因为原子线程栅栏。
int x;
atomic<bool> b(false);
// thread 1:
x = 10;
atomic_thread_fence(memory_order_release);
b = true;
// thread 2:
while(!b){}
atomic_thread_fence(memory_order_acquire);
assert(x == 10); // x will always be 10
但是在下面的代码中,*x 在线程 2 中总是 10 吗?
int* x = new int;
atomic<bool> b(false);
// thread 1:
*x = 10;
atomic_thread_fence(memory_order_release);
b = true;
// thread 2:
while(!b){}
atomic_thread_fence(memory_order_acquire);
assert(*x == 10); // will *x always be 10?
【问题讨论】:
-
我几乎看不出有什么不同。而且我认为由于原子布尔访问,不需要内存围栏。
标签: c++ multithreading pointers atomic