Multiple threads reading static variable at the same time
-
29-10-2019 - |
Question
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.
Solution
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.
OTHER TIPS
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.