多个线程同时读取静态变量
我的问题可能是新手或重复的,但我想知道当多个线程尝试同时读取静态变量时会发生什么。我现在对同步不感兴趣,我只是想知道他们是立即阅读还是轮流阅读?
更新: 我的问题更多是在物理领域或类似的问题(=如果是线程读取变量的同一时刻。
My question may be newbie or duplicate, but i wonder what is happening when several threads try to read a static variable at the same time. I'm not interesting in synchronization now, i just want to know are they reading it instantly or by turn?
UPDATE:
my question is more in domain of physics or smth like that(= if it is the same moment of time when threads read the variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果变量的值不会改变(任何线程都不会写入值),那么多个线程读取将是一个安全的操作,并且不需要像锁定这样的额外同步。否则,您必须考虑锁定写访问操作。
更新:关于问题更新
物理上,在单核CPU的范围内只能执行一条指令(简化的,忽略CPU管道),因此没有机会在同一时间访问相同的内存位置。
If a value of variable does not change (any thread does not write a value) so read by multiple threads would be a safe operation and does not require an additional synchronization like locking. Otherwise you have to consider locking for write access operations.
UPDATE: Regarding question update
Physically in scope of a single core CPU only one instruction (simplified, ignore CPU pipelines) could be executed so no chance to access the same memory location in a same quant of a time.
他们无法真正同时访问它——在某个时刻,CPU 将对读取进行排序。
They can't be accessing it truly simultaneously - at some point the CPU will be sequencing the reads.
如果它是在处理器核心(在所有平台上)中一次读取的静态类型,那么它是一个原子操作。如果它是一个较大的类型,需要多个操作来读取或写入,那么它不是原子的,并且您可以读取由于另一个线程在读取/写入时部分更改它而产生的不可靠值。
If it is a static type that is read in one go a processor core (on all platforms) then it is an atomic operation. If it is a larger type that takes more than one operation to read or write then it is not atomic and you could read dodgy values that are a product of another thread changing it partially while you are reading/writing it.