内容发布更新时间 : 2025/3/30 14:32:51星期一 下面是文章的全部内容请认真阅读。
end
11
b.Varempty,full:semaphore:=1,0; gather: begin repeat ……
gatherdatainnextp; wait(empty); buffer:=nextp; signal(full); untilfalse; end
compute: begin repeat …… wait(full); nextc:=buffer; signal(empty);
computedatainnextc; untilfalse;
end 29.画图说明管程由哪几部分组成,为什么要引入条件变量?
答:管程由四部分组成:①管程的名称;②局部于管程内部的共享数据结构说明; ③对该数据结构进行操作的一组过程;④对局部于管程内部的共享数据设置初始值的语句;
当一个进程调用了管程,在管程中时被阻塞或挂起,直到阻塞或挂起的原因解除, 而在此期间,如果该进程不释放管程,则其它进程无法进入管程,被迫长时间地等待。为了解决这个问题,引入了条件变量condition。 30.如何利用管程来解决生产者与消费者问题?
答:首先建立一个管程,命名为ProclucerConsumer,包括两个过程:(1)Put
10
(item)过程。生产者利用该过程将自己生产的产品放到缓冲池,用整型变
量 count 表示在缓冲池中已有的产品数目,当 count≥n 时,表示缓冲池已满, 生产者须等待。2)get(item)过程。消费者利用该过程从缓冲池中取出一个产品,当 count≤0 时,表示缓冲池中已无可取的产品,消费者应等待。 PC 管程可描述如下: typeproducer-consumer=monitor Varin,out,count:integer; buffer:array[0,…,n-1]ofitem; notfull,notempty:condition; procedureentrydot(item) begin
ifcount>=nthennotfull.wait; buffer(in):=nextp; in:=(in+1)modn; count:=count+1;
ifnotempty.queuethennotempty.signal; end
procedureentryget(item) begin
ifcount<=0thennotfull.wait; nextc:=buffer(out); out:=(out+1)modn; count:=count-1;
ifnotfull.quenethennotfull.signal; end
beginin:=out:=0; count:=0 end
在利用管程解决生产者一消费者问题时,其中的生产者和消费者可描述为: producer:begin pepeat
produceanineminnestp PC.put(item); untilfalse; end
consumer:begin repeat PC.get(item);
consumetheiteminenxtc; untilfalse; end
31.什么是 AND 信号量?试利用 AND 信号量写出生产者一消费者问题的解法。
11
答:为解决并行带来的死锁问题,在wait操作中引入AND条件,其基本思想是将进程在整个运行过程中所需要的所有临界资源,一次性地全