假设我有1个计数器,从值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
变量,然后放置内存获取围栏。
通常,在之前,您必须在之前放置一个释放围栏,然后在读取它之后放置一个获取的围栏。
您可以从Great Jeff Preshing的博客中找到本文中获取/发行记忆围栏的详细说明和示例:http://preshing.com/20130922/acquire-and-release-fences/
线程3(修复函数呼叫顺序后的线程4)不会触发断言,因为与线程之间的同步关系正确。