布尔读/写操作可以在 x86 上不是原子的吗?

2022-01-19 00:00:00 atomic boolean c++ 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).

相关文章