产生死锁
在操作系统中,我们可能接触过两个进程争抢资源,互不相让,然后产生了死锁,这时候,我们可以用银行家算法来分配资源。下面,我们先模拟产生死锁:
#region 试图产生死锁的代码 // static void T1(Program p) //{ // //主线程占有了mainRes并试图访问workerRes; // lock (p.mainRes) // { // Thread.Sleep(10);// // lock (p.workerRes) //死锁 // { // Console.WriteLine(p.workerRes.Data); // } // } //} // void T2() //{ // //工作线程占有了workerRes,并试图访问mainRes; // lock (workerRes) // { // Thread.Sleep(10); // lock (mainRes) // { // Console.WriteLine(mainRes.Data); // } // } //} #endregion
检测死锁
为了检测死锁,我们改进如上代码:
namespace 死锁 { //资源 public class Resource { public string Data; } class Program { private Resource mainRes = new Resource() { Data = "mainRes" }; private Resource workerRes = new Resource() { Data = "workerRes" }; static void Main(string[] args) { Thread.CurrentThread.Name = "main "; Program p = new Program(); Thread worker = new Thread(p.T2); worker.Name = "worker"; worker.Start(); T1(p); } #region 使用Monitor.TryEnter方法——对可能产生死锁的位置进行检测 static void T1(Program p) { lock (p.mainRes ) { Thread.Sleep(10); int i = 0; while (i<3) { if (Monitor.TryEnter (p.workerRes )) { Console.WriteLine(p.workerRes .Data); Monitor.Exit(p.workerRes ); break; } else { Thread.Sleep(1000);//1秒后重试 } i++; } if (i==3) { Console.WriteLine("{0}:tried 3 times,deadlock",Thread.CurrentThread .Name); } } } void T2() { lock (workerRes) { Thread.Sleep(10); int i = 0; while (i < 3) { if (Monitor.TryEnter(mainRes )) { Console.WriteLine(mainRes .Data ); Monitor.Exit(mainRes); break; } else { Thread.Sleep(1000);//1秒后重试 } i++; } if (i == 3) { Console.WriteLine("{0}:tried 3 times,deadlock", Thread.CurrentThread.Name); } } } #endregion } }
如上代码,我们可以使用Monitor.TryEnter方法来对程序中可能产生死锁的位置进行检测。