Programming | multithreading
DeadLockSample.cs
Analyze why deadlocks occur?
Using system;using system.threading;public class test{static readonly Object firstlock = new Object (); Static ReadOnly Object Secondlock = new Object (); static void Main () {New Thread (new ThreadStart (Threadjob)). Start (); Wait until we ' re fairly sure of the other thread//has grabbed Firstlock-thread.sleep (500); Console.WriteLine ("Locking Secondlock"); Lock (Secondlock) {Console.WriteLine ("Locked Secondlock"); Console.WriteLine ("Locking Firstlock"); Lock (Firstlock) {Console.WriteLine ("Locked Firstlock"); } Console.WriteLine ("Released Firstlock"); } Console.WriteLine ("Released Secondlock"); static void Threadjob () {Console.WriteLine ("\t\t\t\tlocking Firstlock"); Lock (Firstlock) {Console.WriteLine ("\t\t\t\tlocked Firstlock"); Wait until we ' rE Fairly sure the "a"/has grabbed Secondlock thread.sleep (1000); Console.WriteLine ("\t\t\t\tlocking Secondlock"); Lock (Secondlock) {Console.WriteLine ("\t\t\t\tlocked Secondlock"); } Console.WriteLine ("\t\t\t\treleased Secondlock"); } Console.WriteLine ("\t\t\t\treleased Firstlock"); }}
Locking Firstlock Locked Firstlock Locking Secondlock Locked Secondlock Locking Firstlock Locking Secondlock |
In response, use Queue and monitor:
QueueMonitorThread.cs
Using system;using system.collections;using system.threading;public class test{static Producerconsumer queue; static void Main () {queue = new Producerconsumer (); New Thread (new ThreadStart (Consumerjob)). Start (); Random rng = new Random (0); for (int i=0 i < i++) {Console.WriteLine ("producing {0}", i); Queue. Produce (i); Thread.Sleep (rng. Next (1000)); } static void Consumerjob () {//Make sure we ' a different random seed from the//A Hread Random rng = new Random (1); We happen to know we have got//items to receive for (int i=0; i < i++) { Object o = queue. Consume (); Console.WriteLine ("\t\t\t\tconsuming {0}", O); Thread.Sleep (rng. Next (1000)); }}public class producerconsumer{ReadOnly Object listlock = new Object (); Queue queue = new Queue (); public void produce (object o) {lock (Listlock) {queue. Enqueue (o); if (queue. Count==1) {monitor.pulse (listlock); }} public object consume () {lock (Listlock) {while queue. count==0) {monitor.wait (listlock); return queue. Dequeue (); } }}
Producing 0 consuming 0 Producing 1 consuming 1 Producing 2 consuming 2 Producing 3 consuming 3 Producing 4 Producing 5 consuming 4 Producing 6 consuming 5 Consuming 6 Producing 7 consuming 7 Producing 8 consuming 8 Producing 9 Consuming 9 |