从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
吗?我知道有些机器缺少一条比较和交换指令,这是原因吗?
最佳答案
首先,完全允许您使用 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.std::atomic<very_nontrivial_large_structure>
之类的东西,因此通常不能保证std::atomic
是无锁的(尽管在大多数系统上,像bool
或int
这样的琐碎类型的大多数专业知识都可以做到)。但这一点无关紧要。
N2427 / 29.3中的注释中给出了为什么atomic_flag
和其他必须必须无锁的确切原因:
换句话说,这是每个平台上必须保证的最低限度的要求,因此可以正确实现该标准。
关于c++ - 为什么只能保证std::atomic_flag是无锁的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301375/