我不知道 std::atomic
变量,但知道 std::mutex
(很奇怪!)由标准提供;但是有一件事引起了我的注意:标准提供了两种看似相同(对我而言)的原子类型,如下所列:
std::atomic_flag
包含以下解释:
std::atomic_flag
is an atomic boolean type. Unlike all specializations ofstd::atomic
, it is guaranteed to be lock-free. Unlikestd::atomic<bool>
,std::atomic_flag
does not provide load or store operations.
我无法理解。是 std::atomic<bool>
不保证无锁?那么它不是原子的还是什么?
那么这两者有什么区别,什么时候应该用哪个呢?
最佳答案
std::atomic bool type not guranteed to be lock-free?
正确。 std::atomic
可以使用锁来实现。
then it's not atomic or what?
std::atomic
无论是否使用锁实现,它都是原子的。 std::atomic_flag
保证在不使用锁的情况下实现。
So what's the difference b/w two
除了无锁保证之外的主要区别是:
std::atomic_flag
does not provide load or store operations.
and when should I use which?
通常,您会想要使用 std::atomic<bool>
当您需要一个原子 bool 变量时。 std::atomic_flag
是一种低级结构,可用于实现自定义原子结构。
关于c++ - 标准的 atomic bool 和 atomic flag 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39329311/