C 获取/发布排序
C++ Acquire/Release Ordering
假设我有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)不会触发断言,因为与线程之间的同步关系正确。
相关文章:
- 合并排序不排序自创建数组类 c++
- 使用 Key 对 C++ 中的哈希映射进行排序. 无法排序
- std::排序为排序自定义对象时出现的向量引发错误
- 队列快速排序不排序和打印随机字符串[C ]
- 插入排序中途排序
- C 排序无法排序一组字符串
- C 选择排序不排序
- 气泡排序不排序
- C++:使用 LSD 基数排序字符串排序崩溃
- C 样式的字符串排序与排序和 qsort
- C++ 快速排序不排序
- 如何对包含 pair<int,int> 元素的向量进行排序?排序是根据比较功能完成的
- Introsort(快速排序+堆排序)实现和复杂性
- 用于排序/操作/排序的最佳替代算法
- 没有严格弱排序的排序集
- STL:指针关联排序容器:排序谓词模板
- 排序和排序有什么区别?
- 寻找c++快速排序/插入排序组合中的错误
- 冒泡排序不排序最后一个数字与此算法
- 选择排序不排序第一个值