"how to make reading this instance primitive thread-safe without locking?" Code Answer


ok, i believe i found the answer and my concern is vindicated!

the code happens to be thread-safe on x86 and amd64 because they invalidate a cpus cache when the variable is written to causing subsequent reads to read the variable from memory. to quote shafqay ahmed quoting jeffrey richter:

since two processors can have different caches, which are copies of the ram, they can have different values. in x86 and x64 processors (according to jeffrey’s book) are designed to sync the caches of different processors so we may not see the problem.

incidentally using lock and interlocked flushes the variable from cache, so using lock when reading the property would have been safe. from http://blogs.msdn.com/b/ericlippert/archive/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three.aspx:

locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given hunk of memory at a time, and so on.

however there is no guarantee in the clr specification given when reading a value updated by another thread (without using locking synchronization constructs) will be the most recent. indeed on arm i could well get an old value using threadsafe class as it is, from http://msdn.microsoft.com/en-us/magazine/jj553518.aspx:

if your code relies on lock-free algorithms that depend on the implementation of the x86 clr (rather than the ecma clr specification), you’ll want to add the volatile keyword to relevant variables as appropriate. once you’ve marked shared state as volatile, the clr will take care of everything for you. if you’re like most developers, you’re ready to run on arm because you’ve already used locks to protect your shared data, properly marked volatile variables and tested your app on arm.

so it seems the answer is i can use a lock when reading or make my field volatile, though perhaps i should use lock and try reduce the number of calls, as a man who worked on the compiler says:

the number of situations in which a lock is too slow is very small, and the probability that you are going to get the code wrong because you don't understand the exact memory model is very large. i don't attempt to write any low-lock code except for the most trivial usages of interlocked operations. i leave the usage of "volatile" to real experts.

By germanfr on August 14 2022

Answers related to “how to make reading this instance primitive thread-safe without locking?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.