Create a deadlock
In the operating system, we may be exposed to two of processes to scramble for resources, and then generate deadlocks, when we can use the banker algorithm to allocate resources. Next, we'll simulate the deadlock:
#region attempting to generate a deadlock code//static void T1 (program P)//{///////////////// main thread occupies Mainres and attempts to access workerres; Lock (P.mainres) // { // Thread.Sleep (Ten)/// Lock (p.workerres) //Deadlock // { // Console.WriteLine (p.workerres.data); } // } //} // void T2 ()//{///// worker thread occupies Workerres and tries to access Mainres; Lock (Workerres) // { // Thread.Sleep (ten); Lock (Mainres) // { // Console.WriteLine (mainres.data); } // } //} #endregion
Deadlock Detection
In order to detect deadlocks, we improved the code as above:
Namespace Deadlock {//Resource 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 Use the Monitor.TryEnter method-detects where a deadlock may have been generated 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 seconds after retry} i++; } if (i==3) {Console.WriteLine ("{0}:tried 3 Times,deadlock", Thread.curre Ntthread. 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 seconds after retry } i++; } if (i = = 3) {Console.WriteLine ("{0}:tried 3 Times,deadlock" , Thread.CurrentThread.Name); }}} #endregion}}
As the code above, we can use the Monitor.TryEnter method to detect where a deadlock can occur in a program.
The generation and detection of deadlock