锁(监视器)在.NET内部实现监视器、NET

2023-09-02 21:20:48 作者:嘴角那一抹浅笑╮

有关掌握了一些技术,你必须知道它是如何做在一个抽象水平。如果多线程编程,这将是很好的了解同步原语。 这是一个问题,如何实现锁(监视器)的.NET?

For mastering of some technology you have to know how it's made at one abstraction level lower. In case of multithreading programming, it will be good to know about synchronization primitives. Here is the question, how implemented Lock (Monitor) in .NET?

我intrested在这样的点: - 它利用OS对象?; - 它需要用户模式或内核模式?; - 什么是开销正在等待锁?; 线程 - 在什么情况下,线程队列中等待的锁也被侵犯

I'm intrested in such points: - does it utilize OS objects?; - does it require user mode or kernel mode?; - what is overhead for threads that are waiting for lock?; - in what cases threads queue that awaiting for the lock could be violated?.

更新: 如果有多个线程将锁,他们排队在就绪队列,并授予先到先得,先到先得锁的注:在Windows中的行为和CLR细微差别意味着,队列的公平性有时会被侵犯。的[果壳中,约瑟夫阿尔巴哈利C#4.0]因此,这是我在问关于最后一个问题,关于'违反队列。

Updated: "If more than one thread contends the lock, they are queued on a "ready queue" and granted the lock on a first-come, first-served basis. Note: Nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated." [C# 4.0 in a Nutshell, Joseph Albahari] So this is what I'm asking about in last question concerning 'violated queue'.

推荐答案

一些调查后,我已经找到了答案,我的问题。在C $ cInChaos和亨克Holterman一般$是正确的,但这里是一些细节。

After some investigations I've found out answers to my questions. In general CodeInChaos and Henk Holterman were right, but here is some details.

当线程开始与其他线程锁争辩首先,它确实自旋等待循环的同时,试图获取锁。所有这一切行动进行中的用户模式的。然后,如果没有成功的操作系统内核对象事件创建,线程从该切换到的内核模式的,等待信号事件

When thread start to contends for a lock with other threads firstly it it does spin-wait loop for a while trying to obtain lock. All this actions performs in user-mode. Then if no success OS kernel object Event creates, thread is switched to the kernel-mode and waits for signal from this Event.

所以,回答我的问题是: 1.在更好的情况下,没有,但更糟糕的是(如果需要的话事件对象懒洋洋地创建); 2.一般工作在用户模式,但如果线程争夺一个锁太久,线程可以切换到内核模式(通过赢API非托管函数调用); 3.开销从用户模式切换到内核模式(〜1000 CPU周期); 4.微软声称它是诚实算法与FIFO相似,但它并不能保证这一点。 (例如,如果从排队等待线程将被移动到队列的末尾将它恢复时暂停。)

So answer to my questions are: 1. In better case no, but in worse yes (Event object lazily creates if required); 2. In general it works in user-mode but if threads compete for a lock too long, thread could be switched to kernel-mode (via Win API unmanaged function call); 3. Overhead for switch from user-mode to kernel-mode (~1000 CPU cycles); 4. Microsoft claim that it is "honest" algorithm like FIFO but it doesn't guarantee this. (E.g. If thread from 'waiting queue' will be suspended it moves to the end of queue when it would be resumed.)