在處理多執行緒同步問題的時候,我們一般有臨界區,互斥量,訊號量和訊息機制等幾種解決方案,在c#中可以非常方便的使用它們來實現程序的同步。下面我就常用的lock,monitor和mutex幾種來說明如何實現程序的同步。
lock和monitor依靠一種「令牌」物件來實現程序的同步,下面看一段示範**:
class example
public void produce()}}
public void consume()}}
}在程式中,我們需要產生兩個生產和消費的執行緒,但是兩個執行緒對count的訪問必須是互斥的,也就是要實現兩個現場的同步。在上面的**中,首先例項化乙個令牌物件o,當需要操作互斥變數count的時候,我就用lock關鍵字去取令牌,如果此時令牌可以拿到,就執行對count的操作,然後釋放令牌。如果此時令牌在另外乙個執行緒手裡,就等待知道該令牌被釋放。monitor的使用與lock很相似,下面附上使用**,不再另加說明:
monitor.enter(o);
count=count+1;
monitor.exit(o);
mutex是使用互斥的機制來實現程序的同步,mutex不需要使用額外的令牌物件。下面是用mutex來解決著名的生產者消費者問題,設定消費者和生產者各3個,公共區容量為5,生產100個,下面看**:
class program
}class produceandconsume
countmux.waitone();//申請公共區數量互斥
if (count >= 5)
else
..", pid);
idmux.releasemutex();
thread.sleep(1);}}
}public void consume()
countmux.waitone();
if (count <= 0)
else
", cid);
idmux.releasemutex();
thread.sleep(1);}}
}}下面是執行結果,可以看到程序已經很好的同步了 :
has produced 1..
has produced 2..
has produced 3..
has produced 4..
has produced 5..
has consume 1
has produced 6..
has consume 2
has consume 3
has consume 4
has produced 7..
has consume 5
has consume 6
has produced 8..
has produced 9..
has consume 7
has produced 10..
has consume 8
has consume 9
has consume 10
has produced 11..
has produced 12..
has consume 11
has produced 13..
has produced 14..
has produced 15..
has consume 12
has produced 16..
has consume 13
has consume 14
has produced 17..
has produced 18..
has consume 15
has produced 19..
has consume 16
has produced 20..
has consume 17
has produced 21..
has produced 22..
has consume 18
has consume 19
has consume 20
has produced 23..
has consume 21
has consume 22
has produced 24..
has consume 23
has produced 25..
has produced 26..
has consume 24
has produced 27..
has consume 25
has consume 26
has produced 28..
has consume 27
has consume 28
has produced 29..
has produced 30..
has consume 29
has produced 31..
has consume 30
has consume 31
has produced 32..
has consume 32
has produced 33..
has produced 34..
has produced 35..
..................................
c 多執行緒中的執行緒同步 Event
互斥量mutex 與 互斥量cs 中,執行緒的編號,也就是i是在主線程中1的,但是子執行緒裡列印出的 i 卻非常混亂,因為主線程裡的寫操作 和子執行緒裡的讀操作是同時進行的,這個有點像資料庫裡的事物,寫操作分為三個步驟,從記憶體中讀取i的值放入暫存器,第二步在暫存器裡加1,第三步寫回記憶體,而子執行...
C 多執行緒同步
在開發中經常會遇到執行緒的例子,如果某個後台操作比較費時間,我們就可以啟動乙個執行緒去執行那個費時的操作,同時程式繼續執行。在某些情況下可能會出現多個執行緒的同步協同的問題,下面的例子就展示了在兩個執行緒之間如何協同工作。這個程式的思路是共同做一件事情 從乙個arraylist中刪除元素 如果執行完...
C 多執行緒 執行緒同步事件
1 事件 事件是核心物件,多用於執行緒間通訊,可以跨程序同步 2 事件使用 1 建立事件 handle createevent lpsecurity attribute slpeventattributes,安全控制,一般直接傳入null bool bmanualreset,確定事件是手動還是自動 ...