管程实现读者优先
Public Database::Read(){
startRead()
read
doneRead()
}
Public Database::Write(){
startWrite()
write
doneWrite()
}
Private Database::startRead(){
lock.Acquire()
while((AW+WW)>0){
WR++
okToRead.wait(lock) //不同于信号量,管程相当于手动控制了阻塞的位置。
WR–
}
AR++
lock.Release()
}
Private Database::doneRead(){
lock.Acquire()
AR–
if (AR==0&&WW>0 ){
okToWrite.signal()
}
lock.Release()
}
Private Database::startWrite(){
lock.Acquire()
while((AR+AW)>0){
WW++
okToWrite.wait(lock)
WW–
}
AW++
lock.Release()
}
Private Database::doneWrite(){
lock.Acquire()
AW–
if (WW>0){
okToWrite.signal()
}
else if (WR>0){
okToRead.broadcast() // 全部唤醒。因为此时写者没了,多个读者可以一起醒来执行。
}
lock.Release()
}