C++:将值赋给原始数据类型(例如 bool)是原子操作吗?
C++: Is the assignment of a value to a primitive data type (e.g. bool) an atomic operation?
假设有两个线程,一个线程为(已初始化的)bool 赋值,另一个线程reading/checking 这个 bool。如果对 bool 的访问不受保护或 bool 是非原子的,则线程清理程序可能会在此处检测到可能的数据竞争。
这怎么可能?是否有可能分配给 bool 并不总是原子的,例如,因为缓存层次结构或乱序执行等硬件特性?
尽管 C++ 标准没有强制要求,但实际上不可能在 x86 上获得 bool
的 撕裂 效果 "in the middle" ,即在另一个线程访问它时仅部分更改该值。但是,可能 CPU 是 maintaining more than one copy of it, as a cache for each core for example. Hence, one thread could be "seeing" an older value after another thread finished changing it to a new one. std::atomic
(and specifically in your case std::atomic<bool>
) provides you with memory barriers 来解决这个问题。
假设有两个线程,一个线程为(已初始化的)bool 赋值,另一个线程reading/checking 这个 bool。如果对 bool 的访问不受保护或 bool 是非原子的,则线程清理程序可能会在此处检测到可能的数据竞争。
这怎么可能?是否有可能分配给 bool 并不总是原子的,例如,因为缓存层次结构或乱序执行等硬件特性?
尽管 C++ 标准没有强制要求,但实际上不可能在 x86 上获得 bool
的 撕裂 效果 "in the middle" ,即在另一个线程访问它时仅部分更改该值。但是,可能 CPU 是 maintaining more than one copy of it, as a cache for each core for example. Hence, one thread could be "seeing" an older value after another thread finished changing it to a new one. std::atomic
(and specifically in your case std::atomic<bool>
) provides you with memory barriers 来解决这个问题。