开发者

are simultaneous reads of a variable thread-safe?

开发者 https://www.devze.com 2023-01-03 13:10 出处:网络
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开发者_JAVA技巧 same time? No this

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开发者_JAVA技巧 same time?


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.


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.


Given that databases can commonly use shared read locks, where any number of clients may read the same block, I would suggest that there are no direct inherent problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号