资源描述:
《读者优先写者优先(PV&管程).doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、读者优先:一个读者试图进行读操作时,如果此时正有其他读者在进行操作,它可以直接开始读操作,不需等待。PV操作varrwmutex,rmutex:semaphore:=1,1;intrcount=0;parbeginprocedurereader(){while(true){P(rmutex);rcount++;if(rcount==1)P(rwmutex);V(rmutex);reading...P(rmutex);rcount--;if(rcount==0)V(rwmutex);V(rmutex);}}procedurewrit
2、er(){while(true){P(rwmutex);writing...V(rwmutex);}}parend管程:typerw=MonitorVarrcount:int;write:boolean;rq,wq:condition;Definestartr,endr,startw,endw;ProcedurestartrBeginif(write)wait(rq);rcount++;signal(rq);EndProcedureendrBeginrcount--;if(rcount==0)signal(wq);EndProce
3、durestartwBeginif(rcount>0orwrite)wait(wq);write=true;EndProcedureendwBeginwrite=false;if(rq!=NULL)signal(rq);elsesignal(wq);EndBeginrcount=0;write=false;Endreader:repeatrw.startr;reading...rw.endr;utilfalsewriter:repeatrw.startw;writing...rw.endw;utilfalse写者优先:一个读者试图
4、进行读操作时,如果有其他写者在等待或进行写操作,它必须等待。PV操作varrwmutex,rmutex,wmutex:semaphore:=1,1,1;intrcount,wcount=0,0;parbeginprocedurereader(){while(true){P(rmutex);rcount++;if(rcount==1)P(rwmutex);V(rmutex);reading...P(rmutex);rcount--;if(rcount==0)V(rwmutex);V(rmutex);}}procedurewriter
5、(){while(true){P(wmutex);wcount++;if(wcount==1)P(rmutex);//waitthereaderV(wmutex);P(rwmutex);writing...V(rwmutex);P(wmutex);wcount--;if(wcount==0)V(rmutex);//signalthereaderV(wmutex);}}parend管程:Typereader_writer=Moniter;Varrq,wq:condition;//就是一个指针rcount,wcount:integer
6、;Definestart_read,finish_read,start_write,finish_write;Procedurestart_readBeginIfwcount>0thenwait(rq);rcount++;signal(rq);End;Procedurefinish_readBeginrcount--;Ifrcount==0thensignal(wq);EndProcedurestart_writeBeginwcount++;Ifwcount>1orrcount>0thenwait(wq);EndProcedure
7、finish_writeBeginwcount--;Ifwcount>0thensignal(wq);elsesignal(rq);EndBeginrcount:=0;wcount:=0;End;reader:rw.start_read;reading...rw.finish_readwriter:rw.start_write;writing...rw.finish_write;typerw=MonitorVarrcount:int;write:boolean;rq,wq:condition;Definestartr,endr,s
8、tartw,endw;ProcedureBeginstartrif(write)wait(rq);rcount++;signal(rq);EndProcedureendrBeginrcount--;if(rcount==0)signal(wq);E