简体   繁体   English

多个线程同时读取静态变量

[英]Multiple threads reading static variable at the same time

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. 更新:我的问题更多的是物理领域或类似的那样(=如果它是线程读取变量的同一时刻。

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的范围内,只能执行一条指令(简化,忽略CPU流水线),因此没有机会在相同的时间内访问相同的存储单元。

他们无法真正同时访问它 - 在某些时候CPU会对读取进行排序。

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. 如果它是一个较大的类型,需要多个操作来读取或写入,那么它不是原子的,您可以读取在您读取/写入时部分更改它的另一个线程的产品的狡猾值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM