C#中使用lock和Monitor控制多線程對資源的使用,最常見的生產者和消費者問題就是多線程同步和通信的經典例子。瞭解C#多線程的同步與通信。 一、關於lock和Monitor lock可以把一段代碼定義為互斥段(critical section),互斥段在一個時刻內只允許一個線程進入執行,而其它 ...
C#中使用lock和Monitor控制多線程對資源的使用,最常見的生產者和消費者問題就是多線程同步和通信的經典例子。瞭解C#多線程的同步與通信。
一、關於lock和Monitor
lock可以把一段代碼定義為互斥段(critical section),互斥段在一個時刻內只允許一個線程進入執行,而其它線程必須等待。格式定義如下:
lock(expression) statement_block
expression代表要跟蹤的對象,通常是引用。一般地,如果想保護一個類的實例,使用this;如果保護一個靜態變數(如互斥代碼段在一個靜態方法內部),使用類名就可以了。而statement_block就是互斥段的代碼。
Monitor用於多線程公用一個對象時使線程共用資源的方案。Monitor必須和一個具體的對象相關聯。
二、生產者和消費者問題
假設兩個線程同時維護一個隊列,如果一個線程對隊列中更新元素,而另外一個線程從隊列中獲取元素,那麼我們稱更新元素的線程為生產者,稱獲取元素的線程為消費者。
1、被操作對象

/// <summary>; /// 被操作對象 /// </summary>; public class Counter { //更新和讀取的數字 private int numberOfCounter; //讀操作可執行標記,可以防止死鎖的發生 private bool readFlag = false; public void Read() { //鎖定後,其它讀操作等待這一次讀操作完成 lock (this) { //第一次之行為flase,進入等待 if (!readFlag) { try { //進入等待讀,另一個線程寫 Monitor.Wait(this); } catch (Exception ex) { Console.WriteLine(ex); } } Console.WriteLine("消費(獲取): {0}", numberOfCounter); //重置,消費已經完成 readFlag = false; Monitor.Pulse(this); } } public void Write(int number) { //鎖定後,其它寫操作等待這一次寫操作完成 lock (this) { //第一次readFlag為flase,跳過執行下邊的寫 //如果當前正在讀,等待讀操作執行Monitor.Pulse if (readFlag) { try { Monitor.Wait(this); } catch (Exception ex) { Console.WriteLine(ex); } } numberOfCounter = number; Console.WriteLine("生產(更新): {0}", numberOfCounter); //重置,生產已經完成 readFlag = true; //同步通過等待Pulse來完成 Monitor.Pulse(this); } } }

2、生產者和消費者

/// <summary>; /// 生產者 /// </summary> public class CounterWrite { Counter counter; //生產者生產次數 int quantity = 1; public CounterWrite(Counter box, int request) { //構造函數 counter = box; quantity = request; } //生產者向操作對象更新信息 public void Write() { for (int i = 1; i <= quantity; i++) counter.Write(i); } } /// <summary> /// 消費者 /// </summary> public class CounterRead { Counter counter; //生產者生產次數 int quantity = 1; public CounterRead(Counter box, int request) { //構造函數 counter = box; quantity = request; } //消費者從操作對象中獲取信息 public void Read() { for (int i = 1; i <= quantity; i++) counter.Read(); } }

3、線程操作

Counter counter = new Counter(); CounterRead read = new CounterRead(counter, 10); CounterWrite write = new CounterWrite(counter, 10); Thread th1 = new Thread(new ThreadStart(read.Read)); Thread th2 = new Thread(new ThreadStart(write.Write)); th1.Start(); th2.Start(); th1.Join(); th2.Join(); Console.ReadLine();

通過lock鎖定Counter對象的引用,初始readFlag為false控制線程1等待讀取:Monitor.Wait(this),
線程2寫入,然後更改readFlag,然後執行:Monitor.Pulse(this),通知等待隊列中的線程請求對象狀態已發生改變,
線程1鎖定this,執行讀操作,然後更改readFlag,線程1和線程2交互執行寫讀的操作。
同時因為readFlag的存在和交替更新,避免了死鎖情況的發生。