问题描述
我有一个问题Monitor.Enter是如何工作的。我调查了.NET Framework的源$ C $ C,它表明这只是:
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);
我想Monitor.Enter实现是与平台相关的,所以我浏览单源$ C $ C,我放弃了:(
I guess Monitor.Enter implementation is platform dependent, so I browsed Mono source code and I gave up :(
是的,分配给每个System.Object的实例可以解决一个关键部分,但是,我不认为实际Monitor.Lock是这样写的,因为创建为每个System.Object的一个关键部分将耗资无限。 (Win32的不允许十亿临界区中的对象的过程!)
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!)
有谁知道Monitor.Enter是如何工作的?请回复。提前致谢。
Does anybody know how Monitor.Enter works? Please reply. Thanks in advance.
推荐答案
纵观单源$ C $ C,似乎他们创建一个信号量(使用的或类似的平台特定的功能),当对象第一次锁定,并将其存储在该对象。此外,还似乎有些对象池正在进行的信号及其相关MonoThreadsSync结构。
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.
相关功能静态内联gint32 mono_monitor_try_enter_internal(MonoObject * OBJ,guint32毫秒,gboolean allow_interruption)
文件单/元/监控研究。 ç
,如果你有兴趣。
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.
我希望微软的.Net做类似的事情。
I expect that Microsoft .Net does something similar.
这篇关于如何System.Threading.Monitor.Enter()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!