简体   繁体   English

C ++获取/发布订单

[英]C++ Acquire/Release Ordering

Let's say I have 1 counter starting at value 2, some non-atomic boolean variable and 4 threads. 假设我有一个从2开始的计数器,一些非原子的布尔变量和4个线程。

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

Thread 1: 线程1:

count.fetch_sub(1, std::memory_order_release);

Thread 2: 线程2:

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

Thread 3: 线程3:

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

Thread 4: 线程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);

Is it possible that the assertions at Thread 3 or Thread 4 may fire? 线程3或线程4的断言是否有可能触发?

Thread 4 may fire the assertion because you use the load operation and the memory fence in incorrect order. 线程4可能会触发该断言,因为您以错误的顺序使用load操作和内存防护。 You have to load the count variable first, then place the memory acquire fence. 您必须先load count变量,然后放置内存获取围栏。
In general case you have to place a Release fence before writing to a synchronization flag and place an Acquire fence after reading it. 通常,您必须写入同步标志之前放置释放防护读取放置获取隔离。

You can find the detailed explanation and examples of Acquire/Release memory fences in this post from the great Jeff Preshing's blog: http://preshing.com/20130922/acquire-and-release-fences/ 您可以在伟大的Jeff Preshing的博客中找到这篇文章中有关获取/释放内存栅栏的详细说明和示例: http ://preshing.com/20130922/acquire-and-release-fences/

Thread 3 (and Thread 4 after fixing the function call order) will not fire an assertion because synchronize-with relationship between threads is established correctly. 线程3(和固定函数调用顺序后的线程4)将不会触发断言,因为线程之间的同步关系已正确建立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM