- 论坛徽章:
- 0
|
西电的操作系统书上关于p-c问题有两个例子,一个是用记录型信号量来解决,一个是用管程,抱歉,用pascal伪码编的,实在没地方问了。
记录型信号量:
Var mutex,empty,full:semaphore:=1,n,0;
buffer:array[0,...,n-1] of item;
in,out:integer:=0,0;
begin
parbegin
proceducer:begin
repeat
...
producer an item nextp;
...
wait(empty);
wait(mutex);
buffer(in):=nextp;
in:=(in+1)mod n;
signal(mutex);
signal(full);
until false;
end
consumer: begin
repeat
walit(full);
wait(mutex);
nextc:=buffer(out);
out:=(out+1)mod n;
signal(mutex);
signal(empty);
consumer the item in nextc;
until false;
end
parend
end
管程:
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 notempty.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
我觉得这两个例子都有问题。
第一个,wait(mutex);(mutex:=1)就等于只允许一个进程访问buffer[n]阿,如果生产者生产产品到buffer[4]的同时,消费者需要消费buffer[3],因为设置了mutex,不就无法实现了吗?但事实上是可以的阿。
第二个,居然没设mutex,我觉得这也不行,因为 buffer[n]毕竟是共享资源,需要互斥使用。
大家说我分析的对吗?如果既要使生产者和消费者在同一时间内互斥的访问buffer[ i ],又可以使同一时间内生产者在访问buffer[ i ],而消费者在访问buffer[j](i!=j),请问应该如何做到呢?
[ 本帖最后由 C文_tinker 于 2008-4-1 11:45 编辑 ] |
|