且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.net 中的死锁示例?

更新时间:2021-11-27 07:54:15

一种常见的方法是,如果嵌套锁的获取顺序不同.线程 1 可以获取锁 A,线程 2 可以获取锁 B 并且它们会死锁.

one common way is if you have nested locks that aren't acquired in the same order. Thread 1 could acquire lock A and thread 2 could acquire lock B and they would deadlock.

var a = new object();
var b = new object();

lock(a) {
   lock(b) {

   }
}

// other thread
lock (b) { 
  lock(a) {

  }
}

非锁定示例 .. 使用等待句柄.假设苏格拉底和笛卡尔正在吃牛排,他们都是彬彬有礼的哲学家,需要叉子和刀子才能吃饭.然而,他们只有一套银器,所以每个人都可以拿起一个餐具,然后永远等待另一个人交出他们的餐具.

edit: non-lock example .. using waithandles. Suppose Socrates and Descartes are having steaks and they both, being well-mannered philosophers, require both a fork and a knife in order to eat. However, they have only one set of silverware, so it is possible for each to grab one utensil and then wait forever for the other to hand over their utensil.

参见餐饮哲学家的问题

WaitHandle fork = new AutoResetEvent(), knife = new AutoResetEvent();

while(Socrates.IsHungry) {
   fork.WaitOne();
   knife.WaitOne();
   Eat();
   fork.Set();
   knife.Set();
} 

// other thread
while(Descartes.IsHungry) {
   knife.WaitOne();
   fork.WaitOne();
   Eat();
   knife.Set();
   fork.Set();
}