第二章 典型练习题目
一生产者--消费者问题扩展 1 扩展一
设有一个可以装A、B两种物品的仓库, 其容量无限大, 但要求仓库中A、B两种物品的数量满足下述不等式: -M≤A物品数量-B物品数量≤N 其中M和N为正整数. 试用信号量和PV操作描述A、B两种物品的入库过程. 问题分析:
若只放入A,而不放入B,则A产品最多可放入N次便被阻塞;若只放入则B产品最多可放入M次便被阻塞;每放入一次A,放入产品B的机会也多一次;同理,每放入一次B,放入产品A的机会也多一次.
The P,V code Using Pascal Semaphore mutex=1,sa=N,sb=M; cobegin
procedure A: procedure B:
while(TURE) while(TURE) begin begin
p(sa); p(sb); p(mutex); p(mutex); A产品入库; B产品入库; V(mutex); V(mutex); V(sb); V(sa); end end
coend
2 扩展二
设有一个可以装A、B两种物品的仓库,其容量有限(分别为两种物品的数量满足下述不等式:
-M≤A物品数量-B物品数量≤N
其中M和N为正整数。另外,还有一个进程消费A,B,一次取一个信号量和PV操作描述A、B两种物品的入库过程。
问题分析:
已知条件-M≤A物品数量-B物品数量≤N 可以拆成两个不等式,即A物品数量-B物品数量≤N B物品数量-A物品数量≤M
这两个不等式的含义是:仓库中A物品可以比B物品多,但不能超过比A物品多,但不能超过M个。
The P,V code Using Pascal semaphore mutex=1,a,b=m,empty1,empty2=N,full1,full2=0; cobegin
process(A); process(B); process(C)
B,而不放入N),但要求仓库中A,B组装成 N个;B物品可以A,A、BC。试用coend
A物品入库 process A
begin
while(TRUE) begin
p(empty1); P(a); p(mutex); A物品入库; v(mutex); V(b); v(full1); end end
B物品入库: process B
begin
while(TRUE) begin
p(empty2); P(b); p(mutex); B物品入库; v(mutex); V(a); p(full2); end end
process C
begin
while(TRUE) begin
p(full1); p(full2); p(a); P(b); 组装; V(a); v(b);
v(empty1);
v(empty2); end
end 3 扩展三
设P,Q,R共享一个缓冲区,P,Q构成一对生产者-消费者,R既为生产者又为消费者。使用P,V 实现其同步。
The P,V code Using Pascal var mutex,full,empty: semaphore; full:=1; empty:=0; mutex:=1; cobegin
Procedure P begin
while true
p(empty); P(mutex); Product one; v(mutex); v(full);
end
Procedure Q begin
while true
p(full); P(mutex); consume one; v(mutex); v(empty);
end
Procedure R begin
if empty:=1 then
begin
p(empty); P(mutex); product; v(mutex); v(full); end if full:=1 then
begin
p(full); p(mutex);
消费一个产品; v(mutex); v(empty); end
coend
二读者--写者问题扩展 1 扩展一
如果读者写者均是平等的即二者都不优先。var w,s,mutex:semaphore; RC:integer; w,s,mutex:=1; RC:=0; cobegin
Procedure Reader begin while TRUE p(w); p(mutex); if RC==0 then p(s); RC:=RC+1; v(mutex); v(w); Reading; p(mutex); RC:=RC-1; if RC==0 then v(s);
v(mutex);
end coend
对读者-写者问题作一条限制,最多只允许量L,赋予其初值为rn,通过执行都要做一次SP(L,1,1)操作,使者必然会因执行SP(L,1,1)操作失败而被封锁。利用一般信号量机制解决读者法描述如下:
The P,V code Using Pascal Procedure Writer begin
while TRUE
p(w); p(s); Writing; v(s); v(w); end rn个读者同时读。为此,又引入了一个信号SP(L,1,1)操作来控制读者的数目,每当一个读者进入时,L的值减1。当有rn个读者进入读后,L便减为The P,V code Using Pascal 0,而第rn+1-写者问题的算 个读
相关推荐: