关于信号量实现读者优先的疑问
匿名2023/07/31 19:49:40提问
    lecture18student
329

课件第十八讲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不能保证谁先执行,不满足读者优先?

百度了一个代码:

  1. /* program readersandwriters*/  
  2. int readcount = 0;  
  3. semaphore x = 1,z = 1, wsem = 1;  
  4. void reader()  
  5. {  
  6.     while(true){  
  7.         semWait(x);  
  8.         readcount ++ ;  
  9.         if(readcount == 1)  
  10.             semWait(wsem);  
  11.         semSignal(x);  
  12.           
  13.         READUNIT();//读数据  
  14.   
  15.         semWait(x);  
  16.         readcount --;  
  17.         if(readcount == 0)  
  18.             semSignal(wsem);  
  19.         semSignal(x);  
  20.     }  
  21. }  
  22. void writer()  
  23. {  
  24.     while(true){  
  25.         semWait(z);//自己加的,不过这样降低了写操作的效率,但满足了以上2点。去除z信号后,就只满足第1点,可以自己分析分析  
  26.         semWait(wsem);  
  27.         WRITEUNIT();//写数据  
  28.         semSignal(wsem);  
  29.         semSignal(z);  
  30.     }  
  31. }  

上面的代码也不对, semSignal(wsem); 和semSignal(z);  可能都执行完再进行调度,仍不能保证读者优先,请教各位,如何才能用信号量实现读者优先。

回答(0
    推荐问答
      Simple Empty
      暂无数据