要求: (1)多个读者可以同时进行读;
(2)写者必须互斥(只允许一个写者写,也不能读者写者同时进行);
(3)写者优先于读者(一旦有写者,则后续读者必须等待,唤醒时优先考虑写者)。
定义读者与写者两个队列: ReadQ与WriterQ,初始值均为空;
定义文件状态 FileState变量,0, write与read三个状态,初始值为0。
若不考虑互斥情况的代码为:
Read()
{
ReadQ.push(); //读者入队
if((ReadQ.Length()!=0)&&(FileState!=write)&&(WriteQ.Length()==0))
{
FileState=read;
ReadQ.do(); //队列中全部读者执行读操作,队列清空
FileState=0;
}
}
Writer()
{
WriterQ.push(); //写者入队
if((WriterQ.Length()!=0)&&(FileState!=read))
{
FileState=write;
writer=WriterQ.pop();
writer.do(); //写者执行写操作
FileState=0;
}
}
考虑到互斥的情况,添加变量readcount,初始值为0,并设置信号量mutex。
对应上面的读者与写者两个队列(ReadQ与WriterQ),文件状态 FileState变量设置三个信号量,依次为mutexReadQ,mutexWriterQ和mutexFileState。
代码如下:
Read()
{
P(mutexWriteQ);
while(WriteQ.Length()!=0)
/*忙等待*/;
V(mutexWriteQ);
P(mutex);
readcount ++;
if (readcount==1)
P(mutexFileState);
V(mutex);
Read.do(); //读者执行读操作
P(mutex);
readcount --;
if (readcount==0)
V(mutexFileState);
V(mutex);
}
Writer()
{
P(mutexWriteQ);
WriterQ.push(); //写者入队
V(mutexWriteQ);
P(mutexFileState);
P(mutexWriteQ);
writer=WriterQ.pop();
V(mutexWriteQ);
writer.do(); //写者执行写操作
V(mutexFileState);
V(mutexWriteQ);
}
阅读(1583) | 评论(0) | 转发(0) |