1、用信号量机制实现的写者优先的算法如 :Var Mut1,Mut2,Wmutex,Fmutex:Semaphore; Rcount,Wcount:integer; Mut1:=Mut2:=WMutex:=Fmutex:=1; Rcount:=Wcount:=0; /Fmutex 读者写者互斥/WMutex 写者互斥/Mut1 access to Rcount Wcount:=Wcount+1; If Wcount=1 then Wait(Fmutex); /如有读者,写者阻塞在此处Signal(Mut1); Wait(WMutex); 写操作; Signal(Wmutex); Wait(Mut1
2、); Wcount:=Wcount-1; If Wcount=0 then Signal(Fmutex); Signal(Mut1); end Reader:begin Wait(Mut1); /读者需要先申请 Mut1,如果有写者在等待 Fmutex,则读者被阻塞,写者优先Signal(Mut1); /立即释放 Mut1,使写者可以随时申请到 Mut1Wait(Mut2); Rcount:=Rcount+1; If Rcount=1 then Wait(Fmutex); /第一个读者进入时,申请 Fmutex;如有写者,第一个读者会阻塞在此处Signal(Mut2); 读操作; Wait(Mut2); Rcount:=Rcount-1; If Rcount=0 then Signal(Fmutex); /最后一个读者退出时,释放 FmutexSingal(Mut2); end