v(wmutex);
p(rwmutex); //其他写进程在rwmutex上排队
write data; //临界区
v(rwmutex); p(wmutex); --writecount;
if(writecount==0) v(x); //写进程都写完时,通过v(x)允许读进程读 v(wmutex); }
附加题:
读者优先,规定仅允许5个进程同时读,怎样修改程序?
解:增加一个资源信号量s,初值为5。 int s=5;
Reader:
begin P(rmutex); readcount=readcount+1; if(readcount==1)then P(rwmutex); V(rmutex); P(s); read_file(); V(s); P(rmutex); readcount=readcount-1; if(readcount==0)then V(rwmutex); V(rmutex); end
writer: