课件第十八讲64页,信号量实现的读者优先:
写者:
P(WriteMutex);
write;
V(WriteMutex);
读者:
P(CountMutex);
if (Rcount == 0)
P(WriteMutex);
++Rcount;
V(CountMutex);
read
P(CountMutex);
--Rcount;
if (Rcount == 0)
V(WriteMutex);
V(CountMutex);
当一个写者A处于write,写者B处于P(WriteMutex);读者C处于
if (Rcount == 0)
P(WriteMutex);
当A执行完毕V(WriteMutex)时,B和C不能保证谁先执行,不满足读者优先?
百度了一个代码:
- /* program readersandwriters*/
- int readcount = 0;
- semaphore x = 1,z = 1, wsem = 1;
- void reader()
- {
- while(true){
- semWait(x);
- readcount ++ ;
- if(readcount == 1)
- semWait(wsem);
- semSignal(x);
-
- READUNIT();//读数据
-
- semWait(x);
- readcount --;
- if(readcount == 0)
- semSignal(wsem);
- semSignal(x);
- }
- }
- void writer()
- {
- while(true){
- semWait(z);//自己加的,不过这样降低了写操作的效率,但满足了以上2点。去除z信号后,就只满足第1点,可以自己分析分析
- semWait(wsem);
- WRITEUNIT();//写数据
- semSignal(wsem);
- semSignal(z);
- }
- }
上面的代码也不对, semSignal(wsem); 和semSignal(z); 可能都执行完再进行调度,仍不能保证读者优先,请教各位,如何才能用信号量实现读者优先。