C#中的重入锁

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/391913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:43:16  来源:igfitidea点击:

Re-entrant locks in C#

c#.netmultithreadinglockingdeadlock

提问by Guy

Will the following code result in a deadlock using C# on .NET?

在 .NET 上使用 C# 以下代码会导致死锁吗?

 class MyClass
 {
    private object lockObj = new object();

    public void Foo()
    {
        lock(lockObj)
        { 
             Bar();
        }
    }

    public void Bar()
    {
        lock(lockObj)
        { 
          // Do something 
        }
    }       
 }

采纳答案by Neil Barnwell

No, not as long as you are locking on the same object. The recursive code effectively already has the lockand so can continue unhindered.

不,只要您锁定同一个对象即可。递归代码实际上已经拥有锁,因此可以不受阻碍地继续。

lock(object) {...}is shorthand for using the Monitorclass. As Marc points out, Monitorallows re-entrancy, so repeated attempts to lock on an object on which the current thread already has a lockwill work just fine.

lock(object) {...}是使用Monitor类的简写。正如Marc 指出的Monitor允许重入,因此重复尝试锁定当前线程已经锁定的对象将工作得很好。

If you start locking on differentobjects, that's when you have to be careful. Pay particular attention to:

如果你开始锁定不同的对象,那你就必须小心了。特别注意:

  • Always acquire locks on a given number of objects in the same sequence.
  • Always release locks in the reversesequence to how you acquire them.
  • 始终以相同的顺序获取给定数量的对象的锁。
  • 始终以与获取锁相反的顺序释放锁。

If you break either of these rules you're pretty much guaranteed to get deadlock issues at some point.

如果您违反这些规则中的任何一个,您几乎可以肯定会在某个时候遇到死锁问题。

Here is one good webpage describing thread synchronisation in .NET: http://dotnetdebug.net/2005/07/20/monitor-class-avoiding-deadlocks/

这是一个很好的网页,描述了 .NET 中的线程同步:http: //dotnetdebug.ne​​t/2005/07/20/monitor-class-avoiding-deadlocks/

Also, lock on as few objects at a time as possible. Consider applying coarse-grained lockswhere possible. The idea being that if you can write your code such that there is an object graph and you can acquire locks on the root of that object graph, then do so. This means you have one lock on that root object and therefore don't have to worry so much about the sequence in which you acquire/release locks.

此外,一次锁定尽可能少的对象。考虑在可能的情况下应用粗粒度锁。这个想法是,如果您可以编写代码使得有一个对象图并且您可以获得该对象图的根上的锁,那么就这样做。这意味着您对该根对象拥有一个锁,因此不必太担心获取/释放锁的顺序。

(One further note, your example isn't technically recursive. For it to be recursive, Bar()would have to call itself, typically as part of an iteration.)

(进一步注意,您的示例在技术上不是递归的。要使其递归,Bar()必须调用自身,通常作为迭代的一部分。)

回答by Marc Gravell

Well, Monitorallows re-entrancy, so you can't deadlock yourself... so no: it shouldn't do

好吧,Monitor允许重入,所以你不能让自己陷入僵局......所以不:它不应该这样做

回答by Jeffrey L Whitledge

If a thread is already holding a lock, then it will not block itself. The .Net framework ensures this. You only have to make sure that two threads do not attempt to aquire the same two locks out of sequence by whatever code paths.

如果一个线程已经持有一个锁,那么它不会阻塞自己。.Net 框架确保了这一点。您只需要确保两个线程不会试图通过任何代码路径无序地获取相同的两个锁。

The same thread can aquire the same lock multiple times, but you have to make sure you release the lock the same number of times that you aquire it. Of course, as long as you are using the "lock" keyword to accomplish this, it happens automatically.

同一个线程可以多次获取同一个锁,但必须确保释放锁的次数与获取它的次数相同。当然,只要您使用“lock”关键字来完成此操作,它就会自动发生。

回答by Rishabh Jain

No, this code will not have dead locks. If you really want to create deadlock simplest one requires at-least 2 resources. Consider dog and the bone scenario. 1. A dog has full control over 1 bone so any other dog has to wait. 2. 2 dog with 2 bones are minimum required to create a deadlock when they lock their bones respectively and seek others bone too.

不,此代码不会有死锁。如果您真的想创建死锁,最简单的方法至少需要 2 个资源。考虑狗和骨头的场景。1. 一只狗可以完全控制 1 块骨头,所以任何其他狗都必须等待。2. 最少需要2只狗,2只骨头,分别锁住自己的骨头,同时寻找其他骨头,才能造成僵局。

.. so on and so forth n dogs and m bones and cause more sophisticated deadlocks.

.. 等等 n 条狗和 m 块骨头,导致更复杂的僵局。