volatile fields and lock

G

Guest

Hello.
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?
Whe using locks, I'm I guaranteed that when accessing shared non-volatile
fields I will get the most up-to-date values?
Thanks.
 
B

Brian Gideon

Amir,

The lock will ensure two things. First, it prevents other threads from
mucking with the shared data which would cause race conditions leading
to potentially half-read or half-written variables. Second, it creates
a memory barrier to ensure that both reads and writes are visible to
all threads and that the ordering of those reads and writes cannot move
beyond the bounds of the lock.

Yes, you are guarenteed to get the most recent value when using the
lock keyword.

For a more detailed explanation read the following article.

http://www.yoda.arachsys.com/csharp/threads/volatility.shtml

Brian
 
C

Chris Mullins

Amir Shitrit said:
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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top