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

标签 c++ multithreading c++11 thread-safety atomic

我不知道 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是一种低级结构,可用于实现自定义原子结构。

关于c++ - 标准的 atomic bool 和 atomic flag 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39329311/

相关文章:

c++ - 我应该更喜欢 std::thread 还是 Boost 线程?

java - 写入同一文件时线程偶尔会阻塞

c++ - 作为回调传递静态方法的地址,其签名来自元组解包

c++ - 访问结构中的字符指针

c++ - 创建一个结构数组但稍后定义大小?

c - pthread_mutex_lock 卡住了

c++ - 这不能用可变参数模板参数包来完成吗?

c++ - 抑制下载速度的变化

c++ - 在 C/C++ 中从 TCP 套接字读取的正确方法是什么?

c++ - COM dll注销问题