c++ - 为什么只能保证std::atomic_flag是无锁的?

标签 c++ multithreading atomic lock-free stdatomic

从C++并发中:

difference between std::atomic and std::atomic_flag is that std::atomic may not be lock-free; the implementation may have to acquire a mutex internally in order to ensure the atomicity of the operations



我想知道为什么。如果保证atomic_flag是无锁的,为什么也不能保证为atomic<bool>
这是因为成员函数compare_exchange_weak吗?我知道有些机器缺少一条比较和交换指令,这是原因吗?

最佳答案

首先,完全允许您使用std::atomic<very_nontrivial_large_structure>之类的东西,因此通常不能保证std::atomic是无锁的(尽管在大多数系统上,像boolint这样的琐碎类型的大多数专业知识都可以做到)。但这一点无关紧要。

N2427 / 29.3中的注释中给出了为什么atomic_flag和其他必须必须无锁的确切原因:

Hence the operations must be address-free. No other type requires lock-free operations, and hence the atomic_flag type is the minimum hardware-implemented type needed to conform to this standard. The remaining types can be emulated with atomic_flag, though with less than ideal properties.



换句话说,这是每个平台上必须保证的最低限度的要求,因此可以正确实现该标准。

关于c++ - 为什么只能保证std::atomic_flag是无锁的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301375/

相关文章:

c++ - 使用变量访问结构中的任何数据?

c++ - 不使用条件变量唤醒线程的最快方法

c# - 如何将 C 指针编码到 C# 结构数组

java - 暂停所有正在运行的线程一段时间

multithreading - 如何从JavaFX中的单独线程更新状态和进度

.net - 线程IO优先级设置

c++ - 如果条件在 C/C++ 中成立,如何自动设置一个值?

java - 更改 "roll back"的最佳方法是什么?

c++ - 从 C++ 文件中读取包含 std::vector 的对象

c++ - to_string(42) 不止一个实例匹配参数