标准的原子布尔值和原子标记之间的区别 [英] difference between standard's atomic bool and atomic flag

查看:90
本文介绍了标准的原子布尔值和原子标记之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wasn't aware of the std::atomic variables but was aware about the std::mutex (weird right!) provided by the standard; however one thing caught my eye: there are two seemingly-same (to me) atomic types provided by the standard, listed below:

  1. std::atomic<bool>

std::atomic_flag

std::atomic_flag包含以下说明:

std::atomic_flag是原子布尔类型.与std::atomic的所有专门技术不同,它保证是无锁的.与std::atomic<bool>不同,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>是无锁的?那不是原子的还是什么?

which I fail to understand. Is std::atomic<bool> not guaranteed to be lock-free? Then it's not atomic or what?

那么两者之间有什么区别,什么时候应该使用呢?

So what's the difference between the two and when should I use which?

推荐答案

std :: atomic bool类型不保证无锁吗?

std::atomic bool type not guranteed to be lock-free?

正确. std::atomic可以使用锁来实现.

Correct. std::atomic may be implemented using locks.

那不是原子的还是什么?

then it's not atomic or what?

std::atomic是原子的,无论是否已使用锁实现.保证std::atomic_flag无需使用锁即可实现.

std::atomic is atomic whether it has been implemented using locks, or without. std::atomic_flag is guaranteed to be implemented without using locks.

那么两个黑白有什么区别

So what's the difference b/w two

除无锁保证外,主要区别在于:

The primary difference besides the lock-free guarantee is:

std::atomic_flag不提供加载或存储操作.

std::atomic_flag does not provide load or store operations.


什么时候应该使用哪个?

and when should I use which?

通常,当需要原子布尔变量时,将要使用std::atomic<bool>. std::atomic_flag是可用于实现自定义原子结构的低级结构.

Usually, you will want to use std::atomic<bool> when you need an atomic boolean variable. std::atomic_flag is a low level structure that can be used to implement custom atomic structures.

这篇关于标准的原子布尔值和原子标记之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆