c++中cppreference中一个多线程示例的解释
Interpretation of a multi-thread example from cppreference in C++
我在cppreference中找到了一个程序:
std::atomic<int> x{0};
int a[] = {1,2};
std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int) {
x.fetch_add(1, std::memory_order_relaxed);
while (x.load(std::memory_order_relaxed) == 1) { } // Error: assumes execution order
});
"错误:假定执行顺序"是什么意思,也就是说,这个程序的错误是什么?程序的目的似乎是显示死锁,但是我看不出来。
我知道标题不清楚,但我真的不知道如何描述这个问题,因为我在程序中找不到任何错误。不好意思
这个例子来自草案(例如N4606 [algorithms.parallel.exec]/3):
(例子:
std::atomic<int> x{0};
int a[] = {1,2};
std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int) {
x.fetch_add(1, std::memory_order_relaxed);
// spin wait for another iteration to change the value of x
while (x.load(std::memory_order_relaxed) == 1) { } // incorrect: assumes execution order
});
上面的示例取决于迭代的执行顺序,如果两个迭代在同一执行线程上顺序执行,则不会终止。- end示例]
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 多线程比没有线程C++慢
- 具有 C++11 多线程的特征库
- 在多线程工作负载上解释Gperftools的结果
- 用于虚拟对象的Linux线程.有人能解释linux中多线程库之间的区别吗
- c++中cppreference中一个多线程示例的解释