"Amir Shitrit" <Am*********@discussions.microsoft.comwrote
How come it's safe to read non-volatile fields that are shared across
threads using locks for synchronization (for example, Monitor.Enter or
EventWaitHandle), but it's not safe to access them if no lock
synchronization mechanisms are employed?
That's a simple question that has a very deep answer. :(
In short, using a threading construct luch as a Monitor places what's called
a Memory Barrier into the code and let's the compiler know that it can't
cache things locally. You can (in .Net 2.0) play some fun Memory Barrier
games, but it's not really worth the trouble.
Whe using locks, I'm I guaranteed that when accessing shared non-volatile
fields I will get the most up-to-date values?
Yup.
Now, if you really want to have fun, go ahead and ask:
- Should you perform Interlocked operations on Volatile variables.
- Why is there no such thing as a 64-bit volatile field?
- If you can access Variable with Interlocked operations, what's the point
of Volatile?
- If you can have Volatile variables, what's the point of Interlocked
Operations?
- Are volatiles thread safe, or do you still need to use locks?
- Why does the Thread Class have VolatileRead and VolatileWrite - Wouldn't
this create oppertunities for weird stale-data issues if it's not accesses
this way in all cases?
--
Chris Mullins, MCSD.NET, MCPD:Enterprise
http://www.coversant.net/blogs/cmullins