在没有锁定的情况下读取同时被修改的整数变量是否安全?

2021-12-28 00:00:00 multithreading concurrency c++

假设我在一个类中有一个整型变量,这个变量可能会被其他线程并发修改.写入受互斥锁保护.我也需要保护读取吗?我听说有一些硬件架构,如果一个线程修改一个变量,另一个线程读取它,那么读取结果将是垃圾;在这种情况下,我确实需要保护读取.不过,我从未见过这样的架构.

Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect reads too? I've heard that there are some hardware architectures on which, if one thread modifies a variable, and another thread reads it, then the read result will be garbage; in this case I do need to protect reads. I've never seen such architectures though.

此问题假设单个事务仅包含更新单个整数变量,因此我不担心也可能涉及事务的任何其他变量的状态.

This question assumes that a single transaction only consists of updating a single integer variable so I'm not worried about the states of any other variables that might also be involved in a transaction.

推荐答案

原子读
如前所述,它依赖于平台.在 x86 上,该值必须在 4 字节边界上对齐.通常对于大多数平台,读取必须在单个 CPU 指令中执行.

atomic read
As said before, it's platform dependent. On x86, the value must be aligned on a 4 byte boundary. Generally for most platforms, the read must execute in a single CPU instruction.

优化器缓存
优化器不知道您正在读取由不同线程修改的值.声明值 volatile 有助于:优化器将为每次访问发出内存读/写,而不是尝试将值缓存在寄存器中.

optimizer caching
The optimizer doesn't know you are reading a value modified by a different thread. declaring the value volatile helps with that: the optimizer will issue a memory read / write for every access, instead of trying to keep the value cached in a register.

CPU 缓存
不过,您可能会读取一个陈旧的值,因为在现代架构中,您有多个内核和单独的缓存,这些缓存不会自动保持同步.您需要一个读内存屏障,通常是一个特定于平台的指令.

CPU cache
Still, you might read a stale value, since on modern architectures you have multiple cores with individual cache that is not kept in sync automatically. You need a read memory barrier, usually a platform-specific instruction.

在 Wintel 上,线程同步函数会自动添加一个完整的内存屏障,或者您可以使用 InterlockedXxxx 函数.

On Wintel, thread synchronization functions will automatically add a full memory barrier, or you can use the InterlockedXxxx functions.

MSDN:内存和同步问题,MemoryBarrier 宏

[edit] 另请参阅 drhirsch 的评论.

[edit] please also see drhirsch's comments.

相关文章