多线程问题--- 死锁

过多的锁定也会有麻烦。在死锁中,至少有两个线程被挂起,并等待对方解除锁定。由于两个线程都在等待对方,就出现了死锁,线程将无限等待下去。

看下面的示例:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Diagnostics;
   6: using System.Threading;
   7: using System.Threading.Tasks;
   8:  
   9: namespace ThreadingIssues
  10: {
  11:     public class StateObject
  12:     {
  13:         private int state = 5;
  14:         private object sync = new object();
  15:         /// <summary>
  16:         /// 当state等于5时,改变state的值
  17:         /// </summary>
  18:         /// <param name="loop"></param>
  19:         public void ChangeState(int loop)
  20:         {
  21:             lock (sync)
  22:             {
  23:                 if (state == 5)
  24:                 {
  25:                     state++;
  26:                     Trace.Assert(state == 6, "Race condition occurred after " + loop + " loops");
  27:                 }
  28:             }
  29:             state = 5;
  30:         }
  31:     }
  32:  
  33:     public class SampleThread
  34:     {
  35:         private StateObject s1;
  36:         private StateObject s2;
  37:  
  38:         public SampleThread(StateObject s1,StateObject s2)
  39:         {
  40:             this.s1 = s1;
  41:             this.s2 = s2;
  42:         }
  43:  
  44:         public void Deadlock1()
  45:         {
  46:             int i = 0;
  47:             while (true)
  48:             {
  49:                 lock (s1)
  50:                 {
  51:                     lock (s2)
  52:                     {
  53:                         s1.ChangeState(i);
  54:                         s2.ChangeState(i++);
  55:                         Console.WriteLine("still running,{0}",i);
  56:                     }
  57:                 }
  58:             }
  59:         }
  60:  
  61:         public void Deadlock2()
  62:         {
  63:             int i = 0;
  64:             while (true)
  65:             {
  66:                 lock (s2)
  67:                 {
  68:                     lock (s1)
  69:                     {
  70:                         s1.ChangeState(i);
  71:                         s2.ChangeState(i++);
  72:                         Console.WriteLine("still running,{0}", i);
  73:                     }
  74:                 }
  75:             }
  76:         }
  77:     }
  78:  
  79:    class Program
  80:     {
  81:         static void Main(string[] args)
  82:         {
  83:             var state1 = new StateObject();
  84:             var state2 = new StateObject();
  85:             new Task(new SampleThread(state1, state2).Deadlock1).Start();
  86:             new Task(new SampleThread(state1, state2).Deadlock2).Start();
  87:         }
  88:     }
  89: }
posted @ 2012-09-29 17:06  美梦成真  阅读(472)  评论(0编辑  收藏  举报