Re: Boolean access in multithreaded environment

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 05/21/04


Date: Fri, 21 May 2004 13:31:04 +0100


 <<ManojM>> wrote:
> I have one thread assigning true/false to boolean and another thread
> accessing the value of the boolean. I need this operation to be thread safe.
> Someone told me that boolean assignment is atomic operation and thats why I
> need not make it volatile. Is it true that its atomic or should I make it
> volatile/restrict its access by lock?

Atomic access and volatilty are somewhat orthogonal issues. Atomic
access means that the value will always be either the old value or the
new value - never some half-way house where part of the new data has
been written and part of it hasn't.

Volatility is to do with whether or not a reading thread "sees" the new
value or whether it could use a cached copy, and whether a writing
thread actually accesses main memory or just changes a cached version
until the cache is flushed.

Restricting access using a lock sorts out both issues, as acquiring a
lock involves a volatile read, and releasing it involves a volatile
write.

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


Relevant Pages

  • Re: 2 different threads checking on same variable scenario
    ... If the sharedVar is a boolean, you don't need any kind of lock. ... unless sharedVar is declared to be volatile. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Boolean access in multithreaded environment
    ... > accessing the value of the boolean. ... > Someone told me that boolean assignment is atomic operation and thats why ... > need not make it volatile. ... > volatile/restrict its access by lock? ...
    (microsoft.public.pocketpc.developer)
  • Boolean access in multithreaded environment
    ... I have one thread assigning true/false to boolean and another thread ... Someone told me that boolean assignment is atomic operation and thats why I ... need not make it volatile. ...
    (microsoft.public.pocketpc.developer)
  • Re: When is "volatile" used instead of "lock" ?
    ... I've been trying to get to your assertion of no JIT optimizations of members ... between Enter/Exit because of "volatility guarantees" in the CLI spec. ... between Enter/Exit were considered volatile operations-which is probably why ... publicly visible object is used as the lock object, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: When is "volatile" used instead of "lock" ?
    ... "lock" cannot not apply. ... > synchronized method) shall implicitly perform a volatile write ... reference used as the parameter for the lock. ... There can be no lock acquire semantics for value members. ...
    (microsoft.public.dotnet.languages.csharp)