expression代表你希望跟蹤的對象,通常是對象引用。一般地,如果你想保護一個類的執行個體,你可以使用this;如果你希望保護一個靜態變數(如互斥程式碼片段在一個靜態方法內部),一般使用類名就可以了。而statement_block就是互斥段的代碼,這段代碼在一個時刻內只可能被一個線程執行。
下面是一個使用lock關鍵字的典型例子,我將在注釋裡向大家說明lock關鍵字的用法和用途:
//lock.cs using System; using System.Threading; internal class Account { int balance; Random r = new Random(); internal Account(int initial) { balance = initial; } internal int Withdraw(int amount) { if (balance < 0) { file://如果balance小於0則拋出異常 throw new Exception("Negative Balance"); } //下面的代碼保證在當前線程修改balance的值完成之前 //不會有其他線程也執行這段代碼來修改balance的值 //因此,balance的值是不可能小於0的 lock (this) { Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name); file://如果沒有lock關鍵字的保護,那麼可能在執行完if的條件判斷之後 file://另外一個線程卻執行了balance=balance-amount修改了balance的值 file://而這個修改對這個線程是不可見的,所以可能導致這時if的條件已經不成立了 file://但是,這個線程卻繼續執行balance=balance-amount,所以導致balance可能小於0 if (balance >= amount) { Thread.Sleep(5); balance = balance - amount; return amount; } else { return 0; // transaction rejected } } } internal void DoTransactions() { for (int i = 0; i < 100; i++) Withdraw(r.Next(-50, 100)); } } internal class Test { static internal Thread[] threads = new Thread[10]; public static void Main() { Account acc = new Account (0); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(acc.DoTransactions)); threads[i] = t; } for (int i = 0; i < 10; i++) threads[i].Name=i.ToString(); for (int i = 0; i < 10; i++) threads[i].Start(); Console.ReadLine(); } } |
而多線程公用一個對象時,也會出現和公用代碼類似的問題,這種問題就不應該使用lock關鍵字了,這裡需要用到System.Threading中的一個類Monitor,我們可以稱之為監視器,Monitor提供了使線程共用資源的方案。
Monitor類可以鎖定一個對象,一個線程只有得到這把鎖才可以對該對象進行操作。對象鎖機制保證了在可能引起混亂的情況下一個時刻只有一個線程可以訪問這個對象。Monitor必須和一個具體的對象相關聯,但是由於它是一個靜態類,所以不能使用它來定義對象,而且它的所有方法都是靜態,不能使用對象來引用。下面代碼說明了使用Monitor鎖定一個對象的情形:
...... Queue oQueue=new Queue(); ...... Monitor.Enter(oQueue); ......//現在oQueue對象只能被當前線程操縱了 Monitor.Exit(oQueue);//釋放鎖 |
如上所示,當一個線程調用Monitor.Enter()方法鎖定一個對象時,這個對象就歸它所有了,其它線程想要訪問這個對象,只有等待它使用Monitor.Exit()方法釋放鎖。為了保證線程最終都能釋放鎖,你可以把Monitor.Exit()方法寫在try-catch-finally結構中的finally代碼塊裡。對於任何一個被Monitor鎖定的對象,記憶體中都儲存著與它相關的一些資訊,其一是現在持有鎖的線程的引用,其二是一個預備隊列,隊列中儲存了已經準備好擷取鎖的線程,其三是一個等待隊列,隊列中儲存著當前正在等待這個對象狀態改變的隊列的引用。當擁有對象鎖的線程準備釋放鎖時,它使用Monitor.Pulse()方法通知等待隊列中的第一個線程,於是該線程被轉移到預備隊列中,當對象鎖被釋放時,在預備隊列中的線程可以立即獲得對象鎖。
下面是一個展示如何使用lock關鍵字和Monitor類來實現線程的同步和通訊的例子,也是一個典型的生產者與消費者問題。這個常式中,生產者線程和消費者線程是交替進行的,生產者寫入一個數,消費者立即讀取並且顯示,我將在注釋中介紹該程式的精要所在。用到的系統命名空間如下:
using System; using System.Threading; |
首先,我們定義一個被操作的對象的類Cell,在這個類裡,有兩個方法:ReadFromCell()和WriteToCell。消費者線程將調用ReadFromCell()讀取cellContents的內容並且顯示出來,生產者進程將調用WriteToCell()方法向cellContents寫入資料。
public class Cell { int cellContents; // Cell對象裡邊的內容 bool readerFlag = false; // 狀態標誌,為true時可以讀取,為false則正在寫入 public int ReadFromCell( ) { lock(this) // Lock關鍵字保證了什麼,請大家看前面對lock的介紹 { if (!readerFlag)//如果現在不可讀取 { try { file://等待WriteToCell方法中調用Monitor.Pulse()方法 Monitor.Wait(this); } catch (SynchronizationLockException e) { Console.WriteLine(e); } catch (ThreadInterruptedException e) { Console.WriteLine(e); } } Console.WriteLine("Consume: {0}",cellContents); readerFlag = false; file://重設readerFlag標誌,表示消費行為已經完成 Monitor.Pulse(this); file://通知WriteToCell()方法(該方法在另外一個線程中執行,等待中) } return cellContents; } public void WriteToCell(int n) { lock(this) { if (readerFlag) { try { Monitor.Wait(this); } catch (SynchronizationLockException e) { file://當同步方法(指Monitor類除Enter之外的方法)在非同步的代碼區被調用 Console.WriteLine(e); } catch (ThreadInterruptedException e) { file://當線程在等待狀態的時候中止 Console.WriteLine(e); } } cellContents = n; Console.WriteLine("Produce: {0}",cellContents); readerFlag = true; Monitor.Pulse(this); file://通知另外一個線程中正在等待的ReadFromCell()方法 } } } |
下面定義生產者CellProd和消費者類CellCons,它們都只有一個方法ThreadRun(),以便在Main()函數中提供給線程的ThreadStart代理對象,作為線程的入口。
public class CellProd { Cell cell; // 被操作的Cell對象 int quantity = 1; // 生產者生產次數,初始化為1 public CellProd(Cell box, int request) { //建構函式 cell = box; quantity = request; } public void ThreadRun( ) { for(int looper=1; looper<=quantity; looper++) cell.WriteToCell(looper); file://生產者向操作對象寫入資訊 } } public class CellCons { Cell cell; int quantity = 1; public CellCons(Cell box, int request) { cell = box; quantity = request; } public void ThreadRun( ) { int valReturned; for(int looper=1; looper<=quantity; looper++) valReturned=cell.ReadFromCell( );//消費者從操作對象中讀取資訊 } } |
然後在下面這個類MonitorSample的Main()函數中我們要做的就是建立兩個線程分別作為生產者和消費者,使用CellProd.ThreadRun()方法和CellCons.ThreadRun()方法對同一個Cell對象進行操作。
public class MonitorSample { public static void Main(String[] args) { int result = 0; file://一個標誌位,如果是0表示程式沒有出錯,如果是1表明有錯誤發生 Cell cell = new Cell( ); //下面使用cell初始化CellProd和CellCons兩個類,生產和消費次數均為20次 CellProd prod = new CellProd(cell, 20); CellCons cons = new CellCons(cell, 20); Thread producer = new Thread(new ThreadStart(prod.ThreadRun)); Thread consumer = new Thread(new ThreadStart(cons.ThreadRun)); //生產者線程和消費者線程都已經被建立,但是沒有開始執行 try { producer.Start( ); consumer.Start( ); producer.Join( ); consumer.Join( ); Console.ReadLine(); } catch (ThreadStateException e) { file://當線程因為所處狀態的原因而不能執行被請求的操作 Console.WriteLine(e); result = 1; } catch (ThreadInterruptedException e) { file://當線程在等待狀態的時候中止 Console.WriteLine(e); result = 1; } //儘管Main()函數沒有傳回值,但下面這條語句可以向父進程返回執行結果 Environment.ExitCode = result; } } |