简体   繁体   English

锁定声明C#

[英]Lock Statement C#

Say I have three threads that need access to a collection and I use a lock block around the access in each thread. 假设我有三个需要访问集合的线程,并且我在每个线程的访问周围使用了一个锁块。 The following happens... 发生以下情况......

(1) Thread 1 gets the lock on the collection (1)线程1获取集合的锁定
(2) Thread 2 gets blocked (2)线程2被阻止
(3) Thread 3 gets blocked (3)线程3被阻塞

When Thread 1 releases the lock, who gets to take the lock next? 当线程1释放锁定时,谁可以接下来锁定? Is it FIFO access? 是FIFO访问吗?

Thanks 谢谢

你不应该关心谁接下来锁。

Your question implies that you are looking for a FIFO behaviour? 您的问题暗示您正在寻找FIFO行为? Then you might want to try this code by Jakub Sloup: 然后你可能想尝试Jakub Sloup的这段代码:

Monitor/lock which remember order in C# to simulate FIFO 监视/锁定,记住C#中的顺序以模拟FIFO

As already mentioned in the other answers there is no guaranteed order waiting threads will receive a lock. 正如在其他答案中已经提到的,没有保证订单等待线程将获得锁定。

Assuming it's like Win32 then the answer is that it might be FIFO but it might not (it be something else). 假设它像Win32那么答案是它可能是FIFO但它可能不是(它是其他东西)。 For example, a higher-priority thread should be first; 例如,优先级较高的线程应该是第一个; but threads can get a temporary boost or drop in their priority depending on what they've been doing recently. 但线程可以暂时提升或降低优先级,具体取决于他们最近在做什么。

As an answer to your question, all threads recieve the monitor.pulse which will then fight over who gets the lock next. 作为你的问题的答案,所有线程接收monitor.pulse,然后将争夺谁接下来的锁定。

I believe that the people at wintellect wrote a blog regarding how this behaviour could lead to an unfair situation, but there is no fairness at all in the monitor. 我相信wintellect的人写了一篇关于这种行为如何导致不公平情况的博客,但监视器中根本没有公平性。

根据定义,答案是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM