问题描述
Wikipedia page说,作者将等待读者释放重试,然后作者将立即为自己和所有后续作者锁定它。
但是想像一下这样的情况:当当前阅读器位于 ENTRY节内时,其他阅读器和写入器同时被readTry
阻止。当前的读者发布readTry
时,如何保证作者将授予使用共享资源的权限?
我的观点是,在readTry.V()
之后,由线程管理器选择要恢复的下一个线程。因此,也许其他读者会进入进入部分。
所以我的问题是:由于第二读者–作家问题的影响,作家在当前读者发布readTry
之后是否确定锁定共享资源?或也许,还有其他读者可以再次阅读资源?
int readcount,writecount; //(initial value = 0)
semaphore rmutex,wmutex,readTry,resource; //(initial value = 1)
//READER
reader() {
<ENTRY Section>
readTry.P(); //Indicate a reader is trying to enter
rmutex.P(); //lock entry section to avoid race condition with other readers
readcount++; //report yourself as a reader
if (readcount == 1) //checks if you are first reader
resource.P(); //if you are first reader,lock the resource
rmutex.V(); //release entry section for other readers
readTry.V(); //indicate you are done trying to access the resource
<CRITICAL Section>
//reading is performed
<EXIT Section>
rmutex.P(); //reserve exit section - avoids race condition with readers
readcount--; //indicate you're leaving
if (readcount == 0) //checks if you are last reader leaving
resource.V(); //if last,you must release the locked resource
rmutex.V(); //release exit section for other readers
}
//WRITER
writer() {
<ENTRY Section>
wmutex.P(); //reserve entry section for writers - avoids race conditions
writecount++; //report yourself as a writer entering
if (writecount == 1) //checks if you're first writer
readTry.P(); //if you're first,then you must lock the readers out. Prevent them from trying to enter CS
wmutex.V(); //release entry section
resource.P(); //reserve the resource for yourself - prevents other writers from simultaneously editing the shared resource
<CRITICAL Section>
//writing is performed
resource.V(); //release file
<EXIT Section>
wmutex.P(); //reserve exit section
writecount--; //indicate you're leaving
if (writecount == 0) //checks if you're the last writer
readTry.V(); //if you're last writer,you must unlock the readers. Allows them to try enter CS for reading
wmutex.V(); //release exit section
}
解决方法
所以我知道 writer 的优先级高于 reader ,并且它没有在维基百科页面中声明