C++ C++;获取/发布订单

C++ C++;获取/发布订单,c++,memory,atomic,lock-free,C++,Memory,Atomic,Lock Free,假设我有一个从值2开始的计数器,一些非原子布尔变量和4个线程 //Initialization (happens before any thread execute). std::atomic<int> count = ATOMIC_VAR_INIT(2); bool someBoolean = false; 线程2: someBoolean = true; count.fetch_sub(1, std::memory_order_release); 线程3: while(cou

假设我有一个从值2开始的计数器,一些非原子布尔变量和4个线程

//Initialization (happens before any thread execute).
std::atomic<int> count = ATOMIC_VAR_INIT(2);
bool someBoolean = false;
线程2:

someBoolean = true;
count.fetch_sub(1, std::memory_order_release);
线程3:

while(count.load(std::memory_order_acquire) != 0);
//Now, we're out of the while loop...
assert(someBoolean);
线程4:

while(std::atomic_thread_fence(std::memory_order_acquire), 
      count.load(std::memory_order_relaxed) != 0);
//Now, we're out of the while loop...
assert(someBoolean);

线程3或线程4上的断言是否可能触发?

线程4可能触发断言,因为您使用
加载操作和内存围栏的顺序不正确。您必须先
加载
计数
变量,然后放置内存获取栅栏。
一般情况下,您必须在写入同步标志之前放置一个释放围栏,在读取同步标志之后放置一个获取围栏

您可以在伟大的Jeff Preshing的博客中找到获取/释放内存围栏的详细说明和示例:

线程3(以及修复函数调用顺序后的线程4)不会触发断言,因为线程之间的同步关系已正确建立

while(std::atomic_thread_fence(std::memory_order_acquire), 
      count.load(std::memory_order_relaxed) != 0);
//Now, we're out of the while loop...
assert(someBoolean);