Home All Groups Group Topic Archive Search About

volatile - small question

Author
4 Apr 2005 9:42 AM
Nick
I am right in thinking that if I have a class that can be accessed by
more than one thread in my application then I should mark *all*
instance variables within that class with the volatile keyword.
Also is it right that if the access to the variable is within a lock
then this is not required, since all 'memory'/caches are up to date

Thanks in advance
Nick

Author
4 Apr 2005 3:41 PM
Willy Denoyette [MVP]
"Nick" <nick_tuc***@hotmail.com> wrote in message
news:a061d649.0504040142.224eedb6@posting.google.com...
>I am right in thinking that if I have a class that can be accessed by
> more than one thread in my application then I should mark *all*
> instance variables within that class with the volatile keyword.
> Also is it right that if the access to the variable is within a lock
> then this is not required, since all 'memory'/caches are up to date
>
> Thanks in advance
> Nick


Use one of the synchronization primitives like Monitors, they have
acquire/release semantics. Use volatile only for special cases of
synchronization, f.i when you realy need to write thread-safe lock-free
code, IMO something which is very hard to be reliably done on the CLR.

Willy.
Are all your drivers up to date? click for free checkup

Author
4 Apr 2005 5:52 PM
Jon Skeet [C# MVP]
Nick <nick_tuc***@hotmail.com> wrote:
> I am right in thinking that if I have a class that can be accessed by
> more than one thread in my application then I should mark *all*
> instance variables within that class with the volatile keyword.

No. I find that volatile is very rarely the way to create thread-safe
classes.

> Also is it right that if the access to the variable is within a lock
> then this is not required, since all 'memory'/caches are up to date

Yes. Like Willy, I'd suggest using the synchronization primitives most
of the time.

See my article on threading at
http://www.pobox.com/~skeet/csharp/threads
for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too



Post Thread options