multi-threading: locking to return a value?

  • Thread starter Thread starter Zeng
  • Start date Start date
Z

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;
}
}
 
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]
 
Back
Top