Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does System.Threading.Monitor.Enter() work?

I got a question how Monitor.Enter works. I investigated .net framework source code, and it shows this only:

    [System.Security.SecurityCritical]  // auto-generated 
    [ResourceExposure(ResourceScope.None)] 
    [MethodImplAttribute(MethodImplOptions.InternalCall)] 
    private static extern void ReliableEnter(Object obj, ref bool lockTaken);

I guess Monitor.Enter implementation is platform dependent, so I browsed Mono source code and I gave up :(

Yes, a critical section assigned for each System.Object instance may solve, but, I don't think the actual Monitor.Lock is written like this, because creating a critical section for each System.Object will cost unlimitedly. (Win32 does not allow billions of critical section objects in a process!)

Does anybody know how Monitor.Enter works? Please reply. Thanks in advance.

like image 893
Hyunjik Bae Avatar asked Jul 21 '11 02:07

Hyunjik Bae


Video Answer


1 Answers

Looking at the Mono source code, it seems that they create a Semaphore (using CreateSemaphore or a similar platform-specific function) when the object is first locked, and store it in the object. There also appears to be some object pooling going on with the semaphores and their associated MonoThreadsSync structures.

The relevant function is static inline gint32 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption) in the file mono/metadata/monitor.c, in case you're interested.

I expect that Microsoft .Net does something similar.

like image 157
Sven Avatar answered Dec 02 '22 03:12

Sven