donRumatta
donRumatta

Reputation: 842

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.

Upvotes: 8

Views: 7510

Answers (3)

sll
sll

Reputation: 62544

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.

Upvotes: 15

AnthonyLambert
AnthonyLambert

Reputation: 8830

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.

Upvotes: 0

Cylindric
Cylindric

Reputation: 5894

They can't be accessing it truly simultaneously - at some point the CPU will be sequencing the reads.

Upvotes: 3

Related Questions