如何利用管程来解决生产者—消费者问题?
答:首先为它们建立一个管程,描述如下: Type producer-consumer=monitor var in, out, count: integer; buffer: array[0,-----,n-1] of item; notfull,notempty:condition; 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 procedure entry get(item) begin if count<=0 then notempyt.wait; nextc:=buffer(out); out:=(out+1) mod n; count:=count-1; if notfull.queue then notfull.signal; end begin in:=out:=0; count:=0; end 生产者和消费者可描述为: 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【解析】第二章 难易度:中
继续答题:下一题