试利用信号量集写出读者—写者问题的解法

2024-12-27 08:01:11
推荐回答(1个)
回答1:

设置互斥信号量wmutex 表示写者间、读者和写者间互斥
用readcount变量来记录读者数

Var rmutex,wmutex: semaphore:=1,1 ;
readcount :integer :=0 ;
begin
parbegin
reader:begin
repeat
P(rmutex)
if readcount=0 then P(wmutex);
readcount=readcount+1;
V(rmutex)
read text
P(rmutex)
readcount=readcount+1;
if readcount=0 then V(wmutex);
V(rmutex)
until false
writer:begin
repeat
P(wmutex);
write text;
V(wmutex);
until false
end
parend
end