管程機制--解決生產者消費者問題
阿新 • • 發佈:2018-11-07
管程機制--解決生產者消費者問題
生產者消費者問題是比較經典的問題。
管程機制的好處在於所有的程序都採用這種機制獲取臨界資源,不需要考慮怎麼解決臨界資源內在的衝突,只需要呼叫管程提供的函式方法就好。
來看下程式碼實現:
管程定義:
moniter procuder_conmuser() { int in,out,count; Item[] buffer[n]; //緩衝池的長度。 Condition notnull,notempty; //條件變數 Entry put(item) { if(count>=n) notfull.wait(); buffer[in]=nextp; in=(in+1)%n; count++; notempty.signal(); } Entry get(item) { if(count==0) notempty.wait(); nextp=buffer[out]; out=(out+1)%n; count--; notfull.signal(); } { in=out=0; count=0; //初始化管程的區域性變數 } }
生產者消費者程序:
void producer(int i) {
while(1) {
produce an Item in nextp;
procuder_conmuser.put(item);
}
}
void consumer(int i) {
while(1) {
consume an Item in nextc;
procuder_conmuser.out(item);
}
}
把同步機制放在管程中,避免訊號量機制中每個程序都要寫訊號量。
這種機制類似於封裝的思想。在你需要上鎖的時候,只需要呼叫鎖的函式。
也便於對鎖的修改。