1.管程(monitors)和定義
P,V操作分散在用戶程序中,系統無法有效的控制盒管理,而且P,V操作使用不當還會引起系統的死鎖,所以產生了新的進程同步工具-------管程。
代表共享資源的數據結構,以及對該共享數據結構實施操作的一組過程所組成的資源管理程序,共同構成了一個OS的資源管理模塊,我們稱之爲管程。
管程由以下幾個部分組成。
一:管程的名稱
二:局部於管程內部的共享數據結構說明
三:對該數據結構進行操作的過程
四:對局部於管程內部的共享數據結構設置初始值的語句(一段代碼)
五:條件變量
其中有三點需要注意:
一:進程互斥的使用管程,管程被進程調用
二:局部於管程內的數據結構,只能被管程的過程所訪問,同時,管程內的過程,也只能訪問局部於管程內的數據結構
三:在管程機制中,有時候引起進程等待。其中wait()表示某種資源佔用而被等待,從而堵塞自己的進程,放棄對管程的互斥權,signal()表示重新啓動一個被堵塞的進程。
管程的一般描述如下:
<span style="font-size:14px;">type<管程名>=monitor
<管程變量說明>;
procedure <過程名>(<形式參數表>);
begin
<過程體>;
end;
.........
procedure <過程名>(<形式參數表>);
begin
<過程體>;
end;
begin
<局部於管程內部的共享數據初始化語句>
end;</span>
===============
2.利用管程解決生產者-消費者(PC)問題
先建立一個管程,名字爲procedure-consumer,其中包括2個過程
一:put(item)過程。procedure生產的產品數記爲count,當count>=n時,表示緩衝池滿,procedure需要等待
二:get (item)過程.。consumer從緩衝池取得產品,當count<=n時,consumer等待。
PC管程描述如下:
<span style="font-size:14px;">type PC=monitor
Var
in,out,count:integer;
buffer:array[0...n-1]of item;
notfull,notempty:condition;
//如果count滿了,那麼不爲滿的進程被堵塞,不爲空的進程被喚醒
procedure entry put(item)
begin
if count>=n then notfull.wait;
buffer(in):=nextp;
in:=(in+1)mod n;
count:=count+1;
if notempty.queue then notempty.signal
end;
//如果count爲0了,那麼不爲空的進程被堵塞,不爲滿的進程被喚醒
procedure entry get(item)
begin
if count<=0 then notempty.wait;
nextc:=buffer(out)
out:=(out+1)mod n;
count:=count-1;
if notfull.queue the notfull.signal;
end;
//局部於管程內部的數據初始化
begin
in:=out:=count:=0;
end;</span>
producer和consumer的進程如下:
<span style="font-size:14px;">producer: begin
repeat
produce an item in nextp;
PC.put(item);
until false;
end
consumer: begin
repeat
PC.get(item)
consume the item in nextc;
until false;
end</span>