
学习了读者、写者问题,在完成读者优先的算法时发觉了一个简单的方法论,感觉豁然开朗,所以首先讲讲我发觉的方法论,然后根据这个来解决这个问题。
1、找出问题 2、分析问题动因 3、根据动因提出解决方案
读者优先:
//此版本有瑕疵,完整版本烦请继续阅读
Semaphore rwmutex = 1;//用于写者与其他读者/写者互斥访问共享数据
int rcount = 0;//读者计数器
cobegin
proceduer reader
{
rcount ++ ;//----------1
if(rcount == 1) P(rwmutex);

//----------2
读数据;//----------3
rcount -- ;
//----------4
if(rount == 0) V(rwmutex);
}
proceduer writer
{
P(rwmuten);
写数据;//----------5
V(rwmutex);
}

coend
以上1-5处就会出现错误,自行剖析~
//完整版本
Semaphore rwmutex = 1;//用于写者与其他读者/写者互斥访问共享数据
Semaphore rmutex = 1;//用于读者互斥访问
int rcount = 0;//读者计数器
cobegin
proceduer reader
{
P(rmutex);//防止“++”操作被打断
rcount ++ ;
if(rcount == 1) P(rwmutex);
V(rmutex);
读数据;
P(rmutex);//防止“--”操作被打断
rcount -- ;
if(rount == 0) V(rwmutex);
V(rmutex);
}
proceduer writer
{
P(rwmuten);
写数据;
V(rwmutex);
}

coend
写者优先:
即唤起时优先考虑写者。
假设读者数固定为10。
Semaphore rwmutex = 1;//用于写者与其他读者/写者互斥的访问共享数据
Semaphore rmutex = 10;//表示最多10个读者进行读操作
cobegin
procedure reader
{
P(rwmutex);//读者、写者互斥
P(rmutex);
V(rwmutex);//释放读写互斥信号量,允许其他读、写进程访问资源;
读数据;

V(rmutex);
}
procedure writer
{
P(rwmutex);
for(int i = 1;i <= 10;i++) P(rmutex);//禁止新读者,并等待已进入的读者退出
写数据;
for(int i = 1;i <= 10;i++) V(rmutex);//恢复允许rmutex 值为10
V(rwmutex);
}
coend
算法代码参考王昭礼的《操作系统之PV金典》