问题 问答题

试修改下面消费者生产者问题解法中的错误
Producer:
Begin
Repeat

Produce an item in nextp;
Wait(mutex);
Wait(empty);
Buffer(in):=nextp;
(in:=(in+1)mod n;)
Signal(mutex);
Until false;
End
Consumer:
Begin
Repeat
Wait(mutex);
Wait(full):
Nextc:=buffer(out);
Out:=out+1;
Signal(mutex);
Consume item in nextc;
Until false;
End

答案

参考答案:Producer:
Begin
Repeat
Produce an item in nextp;
Wait(mutex); (Wait(empty);)
Wait(empty); (Wait(mutex);)
Buffer(in):=nextp;
(in:=(in+1)mod n;)
Signal(mutex);
(signal(full);)
Until false;
End
Consumer:
Begin
Repeat
Wait(mutex); (Wait(full);)
Wait(full); (Wait(mutex);)
Nextc:=buffer(out);
Out:=out+1; (Out:=(out+1)mod n;)
Signal(mutex);
(signal(empty);)
Consume item in nextc;
Until false;
End
见上面右侧括号中为修改后的内容。
做此类改错题,首先要搞清楚本题的意思,能从中找出同步,互斥关系,重点检查两点:①某信号量的P,V操作一定是成对出现的,互斥的在同一进程中,同步的在不同进程中。②对于P操作,先同步后互斥,位置不能颠倒。P,V操作搞定,再看其它内容。

多项选择题
选择题