c++ - 标准的 atomic bool 和 atomic flag 之间的区别

我不知道 std::atomic变量,但知道 std::mutex (很奇怪!)由标准提供;但是有一件事引起了我的注意:标准提供了两种看似相同(对我而言)的原子类型,如下所列:

  1. std::atomic<bool>

  2. std::atomic_flag

std::atomic_flag包含以下解释:

std::atomic_flag is an atomic boolean type. Unlike all specializations of std::atomic, it is guaranteed to be lock-free. Unlike std::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是一种低级结构,可用于实现自定义原子结构。

https://stackoverflow.com/questions/39329311/

相关文章:

c++ - 在函数模板中使用静态局部变量的地址作为类型标识符是否安全?

c++ - C++ 中是否存在比 long long int 更大的类型?

c++ - std::this_thread::yield() 与 std::this_thread

c++ - 特殊情况: Is & faster than %?

c++ - 我真的需要为 const 对象实现用户提供的构造函数吗?

c++ - C 和 C++ 标准之间的关系是什么?

c++ - 我必须明确调用原子加载/存储吗?

c++ - C++ 异常处理如何转化为机器码

c++ - 架构 x86_64 : Compiling problems 的 undefined s

c++ - 如何轻松查看 C/C++ #include 图?