Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are simultaneous reads of a variable thread-safe?

Assuming that the variable isn't in any risk of being modified during the reads, are there any inherent problems in a variable being read by 2 or more threads at the same time?

like image 948
rtpg Avatar asked Jun 13 '10 18:06

rtpg


People also ask

Can two threads read the same variable at the same time?

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.

What happens when two threads access same variable?

Only one thread can read and write a shared variable at a time. When one thread is accessing a shared variable, other threads should wait until the first thread is done. This guarantees that the access to a shared variable is Atomic, and multiple threads do not interfere.

Are variables thread-safe?

On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.

Are reads thread-safe?

Reading from memory is thread-safe, reading from memory that can be written to at the same time isn't safe though. In Python this is less of a problem as a lot of objects are immutable, hence only references are modified in those cases, not the memory itself.


3 Answers

No this operation is not inherently thread safe.

Even though the variable is not currently being written to, previous writes to the variable may not yet be visible to all threads. This means two threads can read the same value and get different results creating a race condition.

This can be prevented though memory barriers, correct use of volatile or a few other mechanisms. We'd need to know more about your environment, in particular the language, to give a complete explanation.

A slight restating of your question though yields a better answer. Assuming there are no more writes and all previous writes are visible to the current thread, then yes reading the value from multiple threads is safe.

like image 39
JaredPar Avatar answered Oct 02 '22 21:10

JaredPar


If your assumption holds, then there are no problems.

like image 53
Platinum Azure Avatar answered Oct 02 '22 21:10

Platinum Azure


As long as it's a plain variable, it's no risk.

If it is a property, reading it can possibly have side effects, so is not guaranteed to be thread safe.

like image 3
Guffa Avatar answered Oct 02 '22 20:10

Guffa