gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:24:17 26 4
gpt4 key购买 nike

摘自 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 这样的简单类型的大多数特化可能可以)。但这有些无关。

确切原因atomic_flag N2427/29.3 的注释中没有给出任何其他必须无锁的内容:

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/30256472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com