Home All Groups Group Topic Archive Search About

multi-threading: locking to return a value?

Author
25 Mar 2005 12:02 AM
Zeng
Is the lock in these two places needed for multi-threading?  I thought
accessing a variable value should already be atomic. Thanks for your help or
comments.

bool stopping = false;

public bool Stopping
    {
        get
        {
            lock (stopLock)
            {
                return stopping;
            }
        }
    }


   public void Stop()
    {
        lock (stopLock)
        {
            stopping = true;
        }
    }

Author
25 Mar 2005 1:13 AM
Dale Preston
What is stopLock?

Dale Preston

Show quote
"Zeng" <Zeng5***@hotmail.com> wrote in message
news:umfBZ5MMFHA.3844@TK2MSFTNGP14.phx.gbl...
> Is the lock in these two places needed for multi-threading?  I thought
> accessing a variable value should already be atomic. Thanks for your help
or
> comments.
>
> bool stopping = false;
>
> public bool Stopping
>     {
>         get
>         {
>             lock (stopLock)
>             {
>                 return stopping;
>             }
>         }
>     }
>
>
>    public void Stop()
>     {
>         lock (stopLock)
>         {
>             stopping = true;
>         }
>     }
>
>
>
Author
25 Mar 2005 2:29 AM
Richard Blewett [DevelopMentor]
Yes they are necessary but not for an obvious reason.

The processor will attempt to cache information fso it doesn't have to re-read from physical memory and can maybe get the value from a register. But each thread gets its own copy of the registers to in this situation you have to ensure that physical memory writing occurs because you have two separate threads accessing the same block of memory. What the lock does is erect a *Memory Barrier* around the access to stopping which forces real writes to the memory. You can achieve the same thing by marking stopping as volatile - i.e.

volatile bool stopping = false;

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

   Is the lock in these two places needed for multi-threading? I thought
accessing a variable value should already be atomic. Thanks for your help or
comments.

bool stopping = false;

public bool Stopping
{
get
{
lock (stopLock)
{
return stopping;
}
}
}


public void Stop()
{
lock (stopLock)
{
stopping = true;
}
}




[microsoft.public.dotnet.languages.csharp]
Author
25 Mar 2005 9:14 AM
Jon Skeet [C# MVP]
Zeng <Zeng5***@hotmail.com> wrote:
> Is the lock in these two places needed for multi-threading?  I thought
> accessing a variable value should already be atomic.

Atomicity isn't all that's required though, unless you don't mind
getting stale data.

See http://www.pobox.com/~skeet/csharp/threads/volatility.shtml

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

AddThis Social Bookmark Button