1.理解生產者和消費者問題
沒有引入信號量時的生產者和消費者進程,什么情況下會出現結果不唯一?什么情況下會出現永遠等待?
用信號解決生產者和消費者的同步與互斥,要求能自己寫出來。
結果不唯一:假如當前的產品數為8,如果生產者生產一件產品投入緩存區,擬執行產品數加一操作;同時消費者取走一樣產品,擬執行產品數減一操作;假如兩者交替執行加一或減一操作,取決於其執行速度,產品數為9或7,但正確為8.
永遠等待:假如消費者讀取產品數為0時,調度程序暫停消費者進程,讓生產者進程運行,生產者加入一個產品,將產品數加一,它便調用wakeup()函數來喚醒消費者;但是消費者未睡眠,則喚醒信號丟失,當消費者下次運行時,因已檢測到產品數為0,於是去睡眠,當生產者將緩沖區填滿后也去睡眠,這就會造成永遠等待。
2.哲學家吃面問題
semaphore fork[5];
for(int i=0; i<5;i++)
fork[i]=1;
cobegin
process philosopher_i( ){
while(ture){
think( );
P(fork[i]);
P(fork[(i+10%5]);
eat();
V(fork[i]);
V(fork[(i+10%5]);
}
}
coend
3.讀寫文件問題
nt readcount=0;
semaphore writeblock=1,mutex=1;
cobegin
process reader_i() {
P(mutex);
readcount++;
if(readcount==1)
P(writerblock);
V(mutex);
/*讀文件*/
P(mutex);
readcount--;
if(readcount==0)
V(writeblock);
V(mutex); }
coend
4.理發師問題
int waiting=0, chairs=n;
semaphore customers=0,barbers=0,mutex=1;
cobegin
process barbers() {
while(ture) {
P(customers);
P(mutex);
waiting--;
V(barbers);
V(mutex);
cuthair(); } }
process customer_i() {
P(mutex);
if(waiting<chairs) {
waiting++;
V(customers);
V(mutex);
P(barbers):
get_haircut();
}
else
V(mutex);
}
coend
5.在一間酒吧里有三個音樂愛好者隊列,第一隊的音樂愛好者只有隨身聽,第二隊只有音樂磁帶,第三隊只有電池。而要聽音樂就必須隨身聽、音樂磁帶和電池這三種物品俱全。酒吧老板一次出售這三種物品中的任意兩種。當一名音樂愛好者得到這三種物品並聽完一首樂曲后,酒吧老板才能再一次出售這三種物品中的任意兩種。於是第二名音樂愛好者得到這三種物品,並開始聽樂曲。全部買賣就這樣進行下去。試用P,v操作正確解決這一買賣。
semaphore muext=1;
cobegin
process boss(){
P(muext);
/*老板任意出售兩種*/
V(muext);
}
process musiclovers_i() {
while(ture){
P(muext);
listening();
V(muext);
} }
coend
6.某銀行有人民幣儲蓄業務,由n個儲蓄員負責。每個顧客進入銀行后先取一個號,並且等着叫號。當一個儲蓄人員空閑下來,就叫下一個號。請用P,V操作正確編寫儲蓄人員和顧客進程的程序。
semaphore customers=0,clerk=0,mutex=n;
int waiting=0;
cobegin
process clerk() {
while(ture){
P(customers);
P(mutex);
waiting--;
V(clerk);
V(mutex);
service();
} }
process customer_i() {
P(mutex);
waiting++;
V(customers);
V(mutex);
P(clerk):
get_service();
}
coend
7.下面是兩個並發執行的進程。它們能正確運行嗎?若不能請舉例說明,並改正之。(5分)
parbegin
var X:integer;
process P1 process P2
var y,z:integer: var t,u:integer;
begin begin
x:=1; x:=0:
y:=0: t=0;
if x≥l then y:=y十1; if x≤l then t:=t+2;
z:=y; u:=t;
end; end;
parend.
parbegin
var x:integer; var s:semaphore:=1;
process P1 process P2
var y,z:integer ; var ,t,u:integer ;
begin begin
P(s); P(s);
x:=1; x:=0;
y:=0; t:=0;
if x>=1 then y:=y+1; if x<=1 then t:=t+2
V(s); V(s);
z:=y; u:=t;
end end
parend
8.在一個盒子里,混裝了相等數量的黑棋子和白棋子,現要用自動分揀系統把黑棋子和白棋子分開,該系統由兩個並發執行的進程P1和P2組成,其中進程P1專門揀黑子,進程P2專門揀白子。規定兩個進程輪流揀子且每個進程每次只揀一個子。當一個進程在揀子時不允許另一個進程去揀子,並設P1先揀。請用P,V操作管理這兩個並發進程,使其能正確實現上述功能。
semaphore S1,S2;
S1=1;S2=0;
cobegin
process P1(){
begin
repeat
P(S1);
揀黑子
V(S2);
until false;
end
}
process P2(){
begin
repeat
P(S2);
揀白子
V(S1);
until false;
end
}
coend.