[英]C++ Acquire/Release Ordering
假设我有一个从2开始的计数器,一些非原子的布尔变量和4个线程。
//Initialization (happens before any thread execute).
std::atomic<int> count = ATOMIC_VAR_INIT(2);
bool someBoolean = false;
线程1:
count.fetch_sub(1, std::memory_order_release);
线程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可能会触发该断言,因为您以错误的顺序使用load
操作和内存防护。 您必须先load
count
变量,然后放置内存获取围栏。
通常,您必须在写入同步标志之前放置释放防护,并在读取后放置获取隔离。
您可以在伟大的Jeff Preshing的博客中找到这篇文章中有关获取/释放内存栅栏的详细说明和示例: http ://preshing.com/20130922/acquire-and-release-fences/
线程3(和固定函数调用顺序后的线程4)将不会触发断言,因为线程之间的同步关系已正确建立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.