2

I understand the concept of a mutex. It was very well explained here.

But now I want to know what a mutex really is. My guess is that .NET is taking some primitive system resource (maybe even just a memory address?) and wrapping it in an object that it calls a mutex.

Anyone know exactly how a mutex is achieved in .NET?

Community
  • 1
  • 1
richard
  • 12,263
  • 23
  • 95
  • 151

2 Answers2

5

How a mutex gets implemented is quite likely hardware-dependent. Most CPUs have some sort of atomic compare-and-swap instruction that provides the guts of the thing.

But yes, under the hood, it's just a semaphore — a thing (word, probably) whose value indicates whether its signaled or not. The OS provides a means for a thread or process to do an idle wait, waiting for the semaphore to enter the desired state. Most implementation, I believe don't guarantee the order in which a thread might gain ownership of a mutex — just because you were first in line, doesn't mean that you'll be the first to get it.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • "it's just a semaphore" - That's what I thought! It seems like it would just be a simple semaphore that's just ratcheted down to one thread getting access to the resource. Is that right? – richard Apr 12 '11 at 06:43
0

http://msdn.microsoft.com/en-us/magazine/cc164040.aspx will give you the details. .NET Mutexes are based at the end of the day, on Win32 thread primitives, though some things are a bit different (remember that the 'lock' statement works on any object, so there are some things in the CLR called SyncBlocks that deal with that).

Ana Betts
  • 73,868
  • 16
  • 141
  • 209