是否可以安全地读取一个整数变量,同时修改而不锁定? [英] Is it safe to read an integer variable that's being concurrently modified without locking?

查看:132
本文介绍了是否可以安全地读取一个整数变量,同时修改而不锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在类中有一个整数变量,这个变量可能会被其他线程同时修改。写由互斥保护。我需要保护读吗?我听说有一些硬件架构,如果一个线程修改一个变量,另一个线程读取它,那么读取结果将是垃圾;在这种情况下,我确实需要保护读。我从来没有见过这样的架构。

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.

这篇关于是否可以安全地读取一个整数变量,同时修改而不锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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