Can a bool read/write operation be not atomic on x86?(布尔读/写操作可以在 x86 上不是原子的吗?)
问题描述
假设我们有两个线程,一个在循环中读取布尔值,另一个可以在特定时间切换它.就我个人而言,我认为这应该是原子的,因为 C++ 中的 sizeof(bool) 是 1 个字节,您不会部分读/写字节,但我想 100% 确定.
Say we have two threads, one is reading a bool in a loop and another can toggle it at certain times. Personally I think this should be atomic because sizeof(bool) in C++ is 1 byte and you don't read/write bytes partially but I want to be 100% sure.
是还是不是?
编辑:
为了将来参考,同样适用于 int 吗?
Also for future reference, does the same apply to int?
推荐答案
这完全取决于您所说的原子"一词的实际含义.
It all depends on what you actually mean by the word "atomic".
您的意思是最终值将一次性更新"(是的,在 x86 上绝对保证一个字节值 - 以及任何正确对齐的值至少高达 64 位),还是如果我将其设置为真(或假),在我设置它之后没有其他线程会读取不同的值"(这不是很确定 - 你需要一个锁定"前缀来保证这一点).
Do you mean "the final value will be updated in one go" (yes, on x86 that's definitely guaranteed for a byte value - and any correctly aligned value up to 64 bits at least), or "if I set this to true (or false), no other thread will read a different value after I've set it" (that's not quite such a certainty - you need a "lock" prefix to guarantee that).
这篇关于布尔读/写操作可以在 x86 上不是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:布尔读/写操作可以在 x86 上不是原子的吗?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
