示例代码使用锁来说明死锁(本) [英] Sample code to illustrate a deadlock by using lock(this)

查看:408
本文介绍了示例代码使用锁来说明死锁(本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过几篇文章和帖子是说锁(本)锁(typeof运算(的MyType))锁(字符串)都是不好的做法,因为另一个线程可以锁定相同的密钥,并导致死锁。为了了解这个问题,我试图创建一些示例代码来说明的僵局,但一直未能环绕此我的头。

I've read several articles and posts that say that lock(this), lock(typeof(MyType)), lock("a string") are all bad practice because another thread could lock on the same key and cause a deadlock. In order to understand this problem, I was trying to create some sample code to illustrate the deadlock but have been unable to wrap my head around this.

有人可以编写代码简洁一点说明这个经典问题?请尽量简短,我只能在较小的块消化代码。

Can someone write a concise bit of code that illustrates this classic problem? Please keep it short, I can digest code in smaller chunks only.

编辑:
我想lassevk总结起来很好;真正的问题是,你失去了你的锁控制。一旦出现这种情况,你无法控制的锁被调用的顺序,而你让一个潜在的死锁情况。

I think lassevk sums it up well; that the real problem is that you have lost control over your locks. Once that happens, you cannot control the order the locks are called, and you are allowing a potential deadlock situation.

锁(本)锁(typeof运算(的MyType))等所有的地方,你选择了一个锁是无法控制的情况。

lock(this), lock(typeof(MyType)), etc all are situations where you have chosen a lock that is impossible to control.

推荐答案

才会发生死锁如果你有一个以上的锁。需要其中两个线程持有一个资源的情况下,其他的需要(这意味着,必须有一个至少两个资源,以及两个线程都尝试获取它们以不同的顺序)

A deadlock will only occur if you have more than one lock. You need a situation where both threads hold a resource that the other needs (which means there has to be a least two resources, and the two threads have to attempt to acquire them in a different order)

因此,一个简单的例子:

So a simple example:

// thread 1
lock(typeof(int)) {
  Thread.Sleep(1000);
  lock(typeof(float)) {
    Console.WriteLine("Thread 1 got both locks");
  }

}

// thread 2
lock(typeof(float)) {
  Thread.Sleep(1000);
  lock(typeof(int)) {
    Console.WriteLine("Thread 2 got both locks");
  }
}



假设两个线程都彼此的一秒钟内启动,他们都将有时间抢到第一锁之前任何人得到的内锁。如果没有睡眠()调用,一个线程最有可能有时间和释放两个锁其他线程,甚至开始了之前。

Assuming both threads are started within a second of each others, they will both have time to grab the first lock before anyone gets to the inner lock. Without the Sleep() call, one of the threads would most likely have time to get and release both locks before the other thread even got started.

这篇关于示例代码使用锁来说明死锁(本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆