views:

240

answers:

1

In .NET the lock keyword is syntactic sugar around Monitor.Enter and Monitor.Exit, so you could say that this code

lock(locker)
{
  // Do something
}

is the same as

Monitor.Enter(locker);
try
{
  // Do Something
}
finally
{
  Monitor.Exit(locker);
}

However the .NET framework also includes the MemoryBarrier class which works in a similar way

Thread.MemoryBarrier();
//Do something
Thread.MemoryBarrier();

I am confused as when I would want to use Thread.MemoryBarrier over the lock/Monitor version? I am made even more confused by a Threading Tutorial which states they function tthe same.

As far as I can see the visible difference is not needing a locking object, which I guess that using Monitor you could do something across threads where MemoryBarrier is on a single thread.

My gut is telling me that another key difference is MemoryBarrier is for variables only and not for methods.

Lastly this is not related to the existing question When to use ‘volatile’ or ‘Thread.MemoryBarrier()’ in threadsafe locking code? (C#), as that is focusing on the volatile keyword which I understand its usage of.

+11  A: 

In my view you should almost never use Thread.MemoryBarrier. This is used for lock-free code - making sure that changes made on one thread are visible to another without incurring the cost of a lock. It does not control thread synchronization, unlike lock. I don't see where in Joe's tutorial he says that MemoryBarrier "functions the same" as lock. Could you explain where exactly you're getting that impression from?

In my view, low level lock-free code is too difficult for almost anyone other than developers whose main proficiency is concurrency. If I want to write some lock-free code, I'll use higher level building blocks built by those developers (such as Parallel Extensions in .NET 4.0) rather than trying to roll my own.

Just as an example, I recently had my eyes opened to the precise meaning of volatile which isn't "always read from main memory, always write directly to main memory". (My own threading tutorial still has that explanation at the moment - something I need to fix at some point.) It's far more subtle than that. This means that some of my previous uses of volatile may well be incorrect.

Jon Skeet
In Joe's tutorial (on the page I link to) search for 'Memory barriers and locking' there is a short paragraph which states they are equivalent "if we ignore a lock’s mutual exclusion guarantee".
Robert MacLean
However ignoring the mutual exclusion makes the comparison kind of pointless since that is an integral component of the locks
Grizzly
@Grizzly: The comparison isn't pointless - it's useful in terms of *fences*. But that's not the same as saying the two things "function the same" - because the mutual exclusion guarantee is the main point of locking.
Jon Skeet