首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C#多線程編程進階(三):Monitor類實現生產者-消費者模式

     編輯:關於C語言

Monitor 鎖定對象機制

多線程共享對象時,lock關鍵字適用於代碼塊同步,而System.Threading.Monitor提供對象級鎖定,更靈活控制共享資源訪問。特點:

  • 靜態類,不可實例化,所有方法均為靜態。
  • Enter(obj)獲取鎖,Exit(obj)釋放鎖,建議置於finally塊確保釋放。
  • 內部維護:持有鎖線程引用、就緒隊列、等待隊列。
  • Pulse(obj)喚醒等待隊列首個線程移入就緒隊列,鎖釋放時即時獲取。

經典生產者-消費者實現

共享對象Cell包含cellContents(數據)、readerFlag(狀態標誌),兩方法協作:

public class Cell {
    int cellContents; bool readerFlag = false;

    public int ReadFromCell() {
        lock(this) {
            if (!readerFlag) {
                try { Monitor.Wait(this); } // 等待生產
                catch (SynchronizationLockException e) { Console.WriteLine(e); }
                catch (ThreadInterruptedException e) { Console.WriteLine(e); }
            }
            Console.WriteLine("Consume: {0}", cellContents);
            readerFlag = false;
            Monitor.Pulse(this); // 通知生產者
        }
        return cellContents;
    }

    public void WriteToCell(int n) {
        lock(this) {
            if (readerFlag) {
                try { Monitor.Wait(this); } // 等待消費
                catch (SynchronizationLockException e) { Console.WriteLine(e); }
                catch (ThreadInterruptedException e) { Console.WriteLine(e); }
            }
            cellContents = n;
            Console.WriteLine("Produce: {0}", cellContents);
            readerFlag = true;
            Monitor.Pulse(this); // 通知消費者
        }
    }
}

兩線程交替執行:生產者寫入→Pulse喚醒消費者→消費者讀取→Pulse喚醒生產者,實現嚴格同步與通訊。Monitor.Wait釋放鎖並進入等待隊列,Pulse遷移線程至就緒隊列,配合lock保證原子性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved