.net Lock用法【转】

lock就是把一段代码定义为临界区,所谓临界区就是同一时刻只能有一个线程来操作临界区的代码,当一个线程位于代码的临界区时,另一个线程不能进入临界区,如果试图进入临界区,则只能一直等待(即被阻止),直到已经进入临界区的线程访问完毕,并释放锁旗标。

其基本使用方式如下:

C-sharp代码
  1. class Test   
  2. {   
  3.     //定义一个私有成员变量,用于Lock   
  4.     private static object lockobj = new object();   
  5.     void DoSomething()   
  6.     {   
  7.         lock (lockobj)   
  8.         {   
  9.             //需要锁定的代码块   
  10.         }   
  11.     }   
  12. }  

最经典的例子,莫过于模拟银行5个窗口取钱操作的例子了,5个窗口是5个线程,都要取钱,但是同一刻只能有一个窗口可以进行真正的取钱操作(钱数的数值计算,剩余多少等这些代码必须定义为临界区),其他只有等待,其代码如下:

C-sharp代码
  1. using System;   
  2. using System.Threading;   
  3.   
  4. class Account    
  5. {   
  6.    int balance;   
  7.   
  8.    Random r = new Random();   
  9.   
  10.    public Account(int initial)    
  11.    {   
  12.       balance = initial;   
  13.    }   
  14.   
  15.    int Withdraw(int amount)    
  16.    {   
  17.   
  18.       // This condition will never be true unless the lock statement   
  19.       // is commented out:   
  20.       if (balance < 0)    
  21.       {   
  22.          throw new Exception("Negative Balance");   
  23.       }   
  24.   
  25.       // Comment out the next line to see the effect of leaving out    
  26.       // the lock keyword:   
  27.       lock (this)   
  28.       {   
  29.          if (balance >= amount)    
  30.          {   
  31.             Console.WriteLine("提款之前余额(Balance before Withdrawal):  " + balance);   
  32.             Console.WriteLine("提款数量(Amount to Withdraw)           : -" + amount);    
  33.             balance = balance - amount;   
  34.             Console.WriteLine("提款之后余额(Balance after Withdrawal) :  " + balance);   
  35.             Console.WriteLine();   
  36.             return amount;   
  37.          }   
  38.          else    
  39.          {   
  40.             return 0; // transaction rejected   
  41.          }   
  42.       }   
  43.    }   
  44.   
  45.    public void DoTransactions()    
  46.    {   
  47.       //模拟100个人来提款,每次提[1-10)元   
  48.       for (int i = 0; i < 100; i++)    
  49.       {   
  50.          Withdraw(r.Next(1, 10));     
  51.       }   
  52.    }   
  53. }   
  54. class Test    
  55. {   
  56.    public static void Main()    
  57.    {   
  58.       Thread[] threads = new Thread[5];   
  59.   
  60.       //总额为100元   
  61.       Account acc = new Account (100);   
  62.   
  63.       //定义并初始化5个线程,模拟银行的5个窗口   
  64.       for (int i = 0; i < 5; i++)    
  65.       {   
  66.          Thread t = new Thread(new ThreadStart(acc.DoTransactions));   
  67.          threads[i] = t;   
  68.       }   
  69.   
  70.       //启动5个线程,模拟银行的5个窗口开始工作   
  71.       for (int i = 0; i < 5; i++)    
  72.       {   
  73.           Console.WriteLine("threads[{0}].Start()", i);   
  74.          threads[i].Start();   
  75.       }   
  76.    }   
  77. }  

运算结果:

threads[0].Start()
threads[1].Start()
提款之前余额(Balance before Withdrawal): 100
提款数量(Amount to Withdraw) : -4
提款之后余额(Balance after Withdrawal) : 96

提款之前余额(Balance before Withdrawal): 96
提款数量(Amount to Withdraw) : -5
提款之后余额(Balance after Withdrawal) : 91

提款之前余额(Balance before Withdrawal): 91
提款数量(Amount to Withdraw) : -4
提款之后余额(Balance after Withdrawal) : 87

提款之前余额(Balance before Withdrawal): 87
提款数量(Amount to Withdraw) : -9
提款之后余额(Balance after Withdrawal) : 78

提款之前余额(Balance before Withdrawal): 78
threads[2].Start()
提款数量(Amount to Withdraw) : -8
提款之后余额(Balance after Withdrawal) : 70

提款之前余额(Balance before Withdrawal): 70
提款数量(Amount to Withdraw) : -6
提款之后余额(Balance after Withdrawal) : 64

提款之前余额(Balance before Withdrawal): 64
提款数量(Amount to Withdraw) : -1
提款之后余额(Balance after Withdrawal) : 63

提款之前余额(Balance before Withdrawal): 63
提款数量(Amount to Withdraw) : -4
提款之后余额(Balance after Withdrawal) : 59

提款之前余额(Balance before Withdrawal): 59
提款数量(Amount to Withdraw) : -2
提款之后余额(Balance after Withdrawal) : 57

提款之前余额(Balance before Withdrawal): 57
提款数量(Amount to Withdraw) : -1
提款之后余额(Balance after Withdrawal) : 56

提款之前余额(Balance before Withdrawal): 56
提款数量(Amount to Withdraw) : -9
提款之后余额(Balance after Withdrawal) : 47

提款之前余额(Balance before Withdrawal): 47
提款数量(Amount to Withdraw) : -7
提款之后余额(Balance after Withdrawal) : 40

提款之前余额(Balance before Withdrawal): 40
提款数量(Amount to Withdraw) : -5
提款之后余额(Balance after Withdrawal) : 35

提款之前余额(Balance before Withdrawal): 35
提款数量(Amount to Withdraw) : -1
提款之后余额(Balance after Withdrawal) : 34

提款之前余额(Balance before Withdrawal): 34
提款数量(Amount to Withdraw) : -1
提款之后余额(Balance after Withdrawal) : 33

提款之前余额(Balance before Withdrawal): 33
提款数量(Amount to Withdraw) : -2
提款之后余额(Balance after Withdrawal) : 31

提款之前余额(Balance before Withdrawal): 31
提款数量(Amount to Withdraw) : -2
提款之后余额(Balance after Withdrawal) : 29

提款之前余额(Balance before Withdrawal): 29
提款数量(Amount to Withdraw) : -3
提款之后余额(Balance after Withdrawal) : 26

提款之前余额(Balance before Withdrawal): 26
提款数量(Amount to Withdraw) : -3
提款之后余额(Balance after Withdrawal) : 23

提款之前余额(Balance before Withdrawal): 23
提款数量(Amount to Withdraw) : -8
提款之后余额(Balance after Withdrawal) : 15

提款之前余额(Balance before Withdrawal): 15
提款数量(Amount to Withdraw) : -6
提款之后余额(Balance after Withdrawal) : 9

提款之前余额(Balance before Withdrawal): 9
提款数量(Amount to Withdraw) : -9
提款之后余额(Balance after Withdrawal) : 0

threads[3].Start()
threads[4].Start()
请按任意键继续. . .

发现窗口1 threads[1].Start()和窗口2 threads[2].Start()先进行取钱,等窗口3 threads[3].Start()和窗口4 threads[4].Start()去取钱的时候,已经没钱了。

使用lock需要注意的地方:

1.lock不能锁定空值
某一对象可以指向Null,但Null是不需要被释放的。

2.lock不能锁定string类型,虽然它也是引用类型的。因为字符串类型被CLR“暂留”
这意味着整个程序中任何给定字符串都只有一个实例,就是这同一个对象表示了所有运行的应用程序域的所有线程中的该文本。因此,只要在应用程序进程中的任何位置处具有相同内容的字符串上放置了锁,就将锁定应用程序中该字符串的所有实例。因此,最好锁定不会被暂留的私有或受保护成员。
3.lock锁定的对象是一个程序块的内存边界
4.值类型不能被lock,因为前文标红字的“对象被释放”,值类型不是引用类型的

5.lock就避免锁定public 类型或不受程序控制的对象。
例如,如果该实例可以被公开访问,则 lock(this) 可能会有问题,因为不受控制的代码也可能会锁定该对象。这可能导致死锁,即两个或更多个线程等待释放同一对象。出于同样的原因,锁定公共数据类型(相比于对象)也可能导致问题。
使用lock(this)的时候,类的成员变量的值可能会被不在临界区的方法改值了

如下面的测试:

C-sharp代码
  1. using System.Threading;   
  2. using System;   
  3. public class ThreadTest   
  4. {   
  5.     private int i = 0;   
  6.     public void Test()   
  7.     {   
  8.         Thread t1 = new Thread(Thread1);   
  9.         Thread t2 = new Thread(Thread2);   
  10.         t1.Start();   
  11.         t2.Start();   
  12.     }   
  13.     public void Thread1()   
  14.     {   
  15.         lock (this)   
  16.         {   
  17.             Console.WriteLine(this.i);   
  18.             Thread.Sleep(1000);   
  19.             Console.WriteLine(this.i);   
  20.         }   
  21.     }   
  22.     public void Thread2()   
  23.     {   
  24.         Thread.Sleep(500);   
  25.         this.i = 1;   
  26.         Console.WriteLine("Change the value in locking");   
  27.     }   
  28. }   
  29. public class ThreadTest2   
  30. {   
  31.     private int i = 0;   
  32.     public void Test()   
  33.     {   
  34.         Thread t1 = new Thread(Thread1);   
  35.         Thread t2 = new Thread(Thread2);   
  36.         t1.Start();   
  37.         t2.Start();   
  38.     }   
  39.     public void Thread1()   
  40.     {   
  41.         lock (this)   
  42.         {   
  43.             Console.WriteLine(this.i);   
  44.             Thread.Sleep(1000);   
  45.             Console.WriteLine(this.i);   
  46.         }   
  47.     }   
  48.     public void Thread2()   
  49.     {   
  50.         lock (this)   
  51.         {   
  52.             Thread.Sleep(500);   
  53.             this.i = 1;   
  54.             Console.WriteLine("Can't change the value in locking");   
  55.         }   
  56.     }   
  57. }   
  58. public class ThreadMain   
  59. {   
  60.     public static void Main()   
  61.     {   
  62.         //ThreadTest b = new ThreadTest();   
  63.         //Thread t = new Thread(new ThreadStart(b.Test));   
  64.         //t.Start();   
  65.   
  66.         ThreadTest2 b2 = new ThreadTest2();   
  67.         Thread t2 = new Thread(new ThreadStart(b2.Test));   
  68.         t2.Start();   
  69.     }   
  70. }  

测试ThreadTest的运行结果:

0
Change the value in locking
1
请按任意键继续. . .

测试ThreadTest2的运行结果:

0
0
Can't change the value in locking
请按任意键继续. . .

发现第一个测试里成员变量i被改值了。

本想在案例一中lock住this对象,让其他的线程不能操作,可是事情不是像我们想象的那样lock(this)是lock this的意思.this中的属性依然能够被别的线程改变.那我们lock住的是什么?是代码段,是lock后面大括号中代码段,这段代码让多个人执行不不被允许的.那返回头来在看lock(this),this是什么意思呢?可以说this知识这段代码域的标志,看看案例二中Thread2.Thread2就明白了,Thread2中的lock需要等到Thread1种lock释放后才开始运行,释放之前一直处于等待状态,这就是标志的表现.
好吧,让我们来了解一下,lock这段代码是怎么运行的.lock语句根本使用的就是Monitor.Enter和Monitor.Exit,也就是说lock(this)时执行Monitor.Enter(this),大括号结束时执行Monitor.Exit(this).他的意义在于什么呢,对于任何一个对象来说,他在内存中的第一部分放置的是所有方法的地址,第二部分放着一个索引,他指向CLR中的SyncBlock Cache区域中的一个SyncBlock.什么意思呢?就是说,当你执行Monitor.Enter(Object)时,如果object的索引值为负数,就从SyncBlock Cache中选区一个SyncBlock,将其地址放在object的索引中。这样就完成了以object为标志的锁定,其他的线程想再次进行Monitor.Enter(object)操作,将获得object为正数的索引,然后就等待。直到索引变为负数,即线程使用Monitor.Exit(object)将索引变为负数。
如果明白了Monitor.Enter的原理,lock当然不再话下.当然lock后括号里面的值不是说把整个对象锁住,而是对他的一个值进行了修改,使别的lock不能锁住他,这才是lock(object)的真面目.

但在实际使用中Monitor还是不推荐,还是lock好的,Monitor需要加上很多try catch才能保证安全性,但lock却帮我们做了,而且lock看起来更优雅.
在静态方法中如何使用lock呢,由于我们没有this可用,所以我们使用typeof(this)好了,Type也有相应的方法地址和索引,所以他也是可以来当作lock的标志的.
但微软不提倡是用public的object或者typeof()或者字符串这样的标志就是因为,如果你的public object在其他的线程中被null并被垃圾收集了,将发生不可预期的错误.

参考:

http://blog.sina.com.cn/s/blog_69f048190100xu2l.html

http://www.cnblogs.com/yangpu/archive/2010/11/12/1875848.html

posted @ 2012-08-20 14:07  清风寻梦  阅读(5258)  评论(1编辑  收藏  举报