views:

74

answers:

5

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?

+2  A: 

If your assumption holds, then there are no problems.

Platinum Azure
Isn't the problem figuring out if his assumption holds? (which it might not, see guffa's answer: http://stackoverflow.com/questions/3033425/are-simultaneous-reads-of-a-variable-thread-safe/3033439#3033439)
Kris
Even though there are currently no writes, a previous right may not yet be visible to all threads creating a race condition. See my answer for more details.
JaredPar
@Kris, @JaredPar: True enough, but I'm answering the OP's question as stated. :-)
Platinum Azure
@Platinum, my point holds even with the question as stated.
JaredPar
A: 

Given that databases can commonly use 'shared read locks' (http://en.wikipedia.org/wiki/Shared_read_lock), where any number of clients may read the same block, I would suggest that there are no direct inherent problems.

obfuscation
A: 

Yes in three characters.

Edit: Whoops. Yes, it's thread safe. No, there are no problems. People usually ask if something is thread-safe, not if it's thread unsafe.

DeadMG
+1  A: 

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.

Guffa
+2  A: 

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.

JaredPar
Good answer though the use of volatile really depends on the language. In c/c++, volatile is a definite false friend as the code generated is very compiler specific and their is no standard to say what a volatile variable should actually do
zebrabox
@zebrabox, very true. I tried to be careful with the answer because it's extremely language + platform specific.
JaredPar