从C ++中的另一个线程读取指针

时间:2017-02-23 11:47:57

标签: c++ multithreading pointers atomicity

在下面的代码中,由于原子线程围栏,线程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?

0 个答案:

没有答案