P(fork[(i+1)mod5]); V(mutex); 吃饭
V(fork[i]);
V(fork[(i+1)mod5]); } while(1);
3-17.
(1)公平竞争(无写者时,读者仍遵循多个读者可以同时读) rmutex互斥共享readcount; rwmutex读写互斥,写写互斥; 读写进程在z上排队。
int rmutex=1,rwmutex=1,readcount=0;
reader:
begin
p(z); //读写进程在z上排队。 p(rmutex);
if(readcount=0) then p(rwmutex); end if
++readcount; v(rmutex);
v(z); //无写者时,多个读者可以同时读. read data; p(rmutex);
--readcount;
if(readcount=0 then v(rwmutex);
end if;
v(rmutex); … end
writer:
begin
p(z); //读写进程在z上排队。 p(rwmutex); write data;
v(rwmutex); v(z); … end
(2)写者优先
int readcount,writecount;
semaphore rmutex=1,wmutex=1,rwmutex=1,z=1,x=1;
reader:
//当来了一个写进程时,通过p(x)禁止其后读进程读,直到写进程写完为止。
while(1){
p(z); //其他读进程在z上排队
p(x); //一个读进程与一个写进程在x上竞争 p(rmutex); //读进程互斥访问readcount ++readcount;
if(readcount==1) p(rwmutex); v(rmutex); v(x); v(z); read data; //临界区
p(rmutex); --readcount;
if(readcount==0) v(rwmutex); v(rmutex);
}
Writer:
while(1){
p(wmutex); //写进程互斥访问writecount ++writecount;
if(writecount==1) p(x); //一个写进程与一个读进程在x上竞争