.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是不需要被釋放的。(請參考:認識全面的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並被垃圾收集了,將發生不可預期的錯誤.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM