|
ms
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
multi-threading: locking to return a value?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; } } 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; > } > } > > > 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] Zeng <Zeng5***@hotmail.com> wrote:
> Is the lock in these two places needed for multi-threading? I thought Atomicity isn't all that's required though, unless you don't mind > accessing a variable value should already be atomic. 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
Other interesting topics
|
|||||||||||||||||||||||