布尔读/写操作在 x86 上不是原子的吗? [英] Can a bool read/write operation be not atomic on x86?

查看:27
本文介绍了布尔读/写操作在 x86 上不是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个线程,一个在循环中读取 bool,另一个可以在特定时间切换它.我个人认为这应该是原子的,因为 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 位),还是如果我将其设置为true(或 false),在我设置它之后没有其他线程会读取不同的值"(这不是很确定 - 您需要一个锁定"前缀来保证这一点).

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 上不是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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