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?
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.
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.
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.
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.
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.
If your assumption holds, then there are no problems.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With