using system;
using system.threading;
//我們定義乙個被操作的物件的類cell,在這個類裡,有兩個方法:readfromcell()和writetocell。
//消費者執行緒將呼叫readfromcell()讀取cellcontents的內容並且顯示出來,生產者程序將呼叫writetocell()方法向cellcontents寫入資料。
public class cell
catch (synchronizationlockexception e)
catch (threadinterruptedexception e)
}console.writeline("consume: ",cellcontents);
readerflag = false; //重置readerflag標誌,表示消費行為已經完成
monitor.pulse(this); //通知writetocell()方法(該方法在另外乙個執行緒中執行,等待中)
}return cellcontents;
}public void writetocell(int n)
catch (synchronizationlockexception e)
catch (threadinterruptedexception e)
}cellcontents = n;
console.writeline("produce: ",cellcontents);
readerflag = true;
monitor.pulse(this); //通知另外乙個執行緒中正在等待的readfromcell()}}
}//下面定義生產者cellprod和消費者類cellcons,它們都只有乙個方法threadrun(),
//以便在main()函式中提供給執行緒的threadstart**物件,作為執行緒的入口。
public class cellprod
public void threadrun( )
} public class cellcons
public void threadrun( )
}//然後在下面這個類monitorsample的main()函式中我們要做的就是建立兩個執行緒分別作為生產者和消費者,
//使用cellprod.threadrun()方法和cellcons.threadrun()方法對同乙個cell物件進行操作。
public class monitorsample
catch (threadstateexception e)
catch (threadinterruptedexception e)
//儘管main()函式沒有返回值,但下面這條語句可以向父程序返回執行結果
environment.exitcode = result;
}} //同步是通過等待monitor.pulse()來完成的。首先生產者生產了乙個值,而同一時刻消費者處於等待狀態,
//直到收到生產者的「脈衝(pulse)」通知它生產已經完成,此後消費者進入消費狀態,
//而生產者開始等待消費者完成操作後將呼叫monitor.pulese()發出的「脈衝」。它
生產者消費者 生產者與消費者模式
一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...
生產者與消費者
include include include include include include define size of buffer 10 int buffer size of buffer 緩衝陣列 int in 0,out 0 採用迴圈佇列方式進行陣列的訪問 宣告訊號量 sem t ful...
生產者與消費者
include include include include include include handle mutex 互斥訊號量 handle full 滿緩衝區訊號量計數 handle empty 空緩衝區訊號量計數 void producer 生產者函式 void consumer 消費者函...