我什么时候真的需要使用 atomic<bool>而不是布尔? [英] When do I really need to use atomic<bool> instead of bool?

查看:35
本文介绍了我什么时候真的需要使用 atomic<bool>而不是布尔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

atomic 不是多余的,因为 bool 本质上是原子的吗?我认为不可能有部分修改的 bool 值.我什么时候真的需要使用 atomic 而不是 bool?

Isn't atomic<bool> redundant because bool is atomic by nature? I don't think it's possible to have a partially modified bool value. When do I really need to use atomic<bool> instead of bool?

推荐答案

没有 C++ 中的类型是原子性的",除非它是 std::atomic*-某物.那是因为标准是这么说的.

No type in C++ is "atomic by nature" unless it is an std::atomic*-something. That's because the standard says so.

在实践中,用于操作 std::atomic 的实际硬件指令可能(也可能不)与普通 bool 相同code>,但原子性是一个更大的概念,具有更广泛的影响(例如对编译器重新排序的限制).此外,某些操作(如否定)在原子操作上重载,以在硬件上创建与非原子变量的本机、非原子读-修改-写序列截然不同的指令.

In practice, the actual hardware instructions that are emitted to manipulate an std::atomic<bool> may (or may not) be the same as those for an ordinary bool, but being atomic is a larger concept with wider ramifications (e.g. restrictions on compiler re-ordering). Furthermore, some operations (like negation) are overloaded on the atomic operation to create a distinctly different instruction on the hardware than the native, non-atomic read-modify-write sequence of a non-atomic variable.

这篇关于我什么时候真的需要使用 atomic&lt;bool&gt;而不是布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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