[英]difference between standard's atomic bool and atomic flag
I wasn't aware of the std::atomic
variables but was aware about the std::mutex
(weird right!) provided by the standard;我不知道std::atomic
变量,但知道std::mutex
提供的std::mutex
(很奇怪!); however one thing caught my eye: there are two seemingly-same (to me) atomic types provided by the standard, listed below:然而,有一件事引起了我的注意:标准提供了两种看似相同(对我而言)的原子类型,如下所列:
The std::atomic_flag
contains the following explanation: std::atomic_flag
包含以下解释:
std::atomic_flag
is an atomic boolean type.std::atomic_flag
是一个原子布尔类型。 Unlike all specializations ofstd::atomic
, it is guaranteed to be lock-free.与std::atomic
所有特化不同,它保证是无锁的。 Unlikestd::atomic<bool>
,std::atomic_flag
does not provide load or store operations.与std::atomic<bool>
,std::atomic_flag
不提供加载或存储操作。
which I fail to understand.我不明白。 Is std::atomic<bool>
not guaranteed to be lock-free? std::atomic<bool>
不能保证是无锁的吗? Then it's not atomic or what?那么它不是原子的还是什么?
So what's the difference between the two and when should I use which?那么两者之间有什么区别,我应该什么时候使用哪个呢?
std::atomic bool type not guranteed to be lock-free? std::atomic bool 类型不保证无锁?
Correct.正确。 std::atomic
may be implemented using locks. std::atomic
可以使用锁来实现。
then it's not atomic or what?那么它不是原子的还是什么?
std::atomic
is atomic whether it has been implemented using locks, or without.无论是否使用锁实现, std::atomic
都是原子的。 std::atomic_flag
is guaranteed to be implemented without using locks. std::atomic_flag
保证在不使用锁的情况下实现。
So what's the difference b/w two那么黑白两个有什么区别
The primary difference besides the lock-free guarantee is:除了无锁保证之外的主要区别是:
std::atomic_flag
does not provide load or store operations.std::atomic_flag
不提供加载或存储操作。
and when should I use which?我什么时候应该使用哪个?
Usually, you will want to use std::atomic<bool>
when you need an atomic boolean variable.通常,当您需要原子布尔变量时,您将需要使用std::atomic<bool>
。 std::atomic_flag
is a low level structure that can be used to implement custom atomic structures. std::atomic_flag
是一个低级结构,可用于实现自定义原子结构。
std::atomic<T>
guarantees that accesses to the variable will be atomic. std::atomic<T>
保证对变量的访问是原子的。 It however does not says how is the atomicity achieved.然而,它并没有说明如何实现原子性。 It can be using lock-free variable, or using a lock.它可以使用无锁变量,也可以使用锁。 The actual implementation depends on your target architecture and the type T
.实际实现取决于您的目标架构和类型T
。
std::atomic_flag
on the other hand is guaranteed to be implemented using a lock-free technique.另一方面, std::atomic_flag
保证使用无锁技术实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.