Groups | Blog | Home
all groups > dotnet clr > december 2003 >

dotnet clr : Difference between Monitor and Mutex


Gianluca Varenni
12/11/2003 8:32:26 PM
Hi all.

What's the difference, from the OS point of view, between Monitors and
Mutexes?

I'm almost sure that the Mutex object is a wrapper to the native win32 mutex
(if I create a named managed Mutex, I can see it with winobj)

Is there a relationship between the win32 native "CriticalSection" and
Monitors? How are Monitors internally implemented?

Have a nice day
GV

Sherif ElMetainy
12/12/2003 6:13:23 AM
Hello

As you said the Mutex object is a wrapper to the native win32 mutex,
The Monitor is very similar to native win32 CriticalSection but is not a
wrapper to CriticalSection.

The mutex is a kernel object so creating a mutex take more resources and CPU
than creating a monitor, because it requires user mode to kernel mode
transition. The benefit of a mutex is that you can wait for several events /
mutexes using either WaitAny or WaitAll, and you can create a named mutex
that can be used accross 2 or more processes. This applies to both .NET
mutex and win32 native mutex.

As for Monitor, it works in user mode, so takes less resources and CPU than
a mutex. Every object allocated in the heap in .NET framework, has 8 extra
bytes (for 32 bit systems) 4 bytes are the virtual method table, and the
other 4 bytes are the synblockindex, the synblockindex is used by the CLR
for monitor class, and I think the CLR has some internal structure and/or
tables for acquired locks, I don't know the details though.

Best regards,
Sherif

[quoted text, click to view]

Gianluca Varenni
12/12/2003 9:17:28 AM

[quoted text, click to view]


Thank you!
I suspected that the monitor used the syncblockindex (I remember of that
dword when I had a look at the book on Rotor). I think I should have a look
at the rotor source code (the main problem is that is HUGE).

Have a nice day
GV


[quoted text, click to view]

William Stacey
12/14/2003 5:29:21 PM
I have not confirmed this, but I suspect it uses a win32 spinlock for the
enter/exit on the lock and blends an event object into the class for the
pulse and wait methods. Not sure the rotor code would reflect the .net
implementation totally.

--
William Stacey, MVP

[quoted text, click to view]

Peter Koen
12/14/2003 7:07:02 PM
"Gianluca Varenni" <gianluca.varenni@polito.it> wrote in
news:edNPlhIwDHA.1600@TK2MSFTNGP10.phx.gbl:

[quoted text, click to view]

Hi,

A very good explanation of this can be found in the Wrox Book "Advanced
..NET Programming" by Simon Robinson. Although I'm not sure where to get the
book since Wrox doesn't exist anymore.

greets
Peter

--
------ooo---OOO---ooo------

Peter Koen - www.kema.at
MCAD MCDBA
CAI/RS CASE/RS IAT

AddThis Social Bookmark Button