.net 中的死锁示例? [英] Deadlock sample in .net?

查看:25
本文介绍了.net 中的死锁示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能在 C# 中给出一个简单的死锁示例代码?并请说出在您的 C# 代码示例中找到死锁的最简单方法.(可能是给定示例代码中检测死锁的工具.)

Can anybody give a simple Deadlock sample code in c# ? And please tell the simplest way to find deadlock in your C# code sample. (May be the tool which will detect the dead lock in the given sample code.)

注意:我有 VS 2008

NOTE: I have VS 2008

推荐答案

一种常见的方法是,如果嵌套锁的获取顺序不同.线程 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();
} 

这篇关于.net 中的死锁示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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