1.当低优先级进程(线程)获得临界区时,高优先级进程能很快从低优先级的进程中抢得访问权。
2.当高优先级的进程获得临界区访问权时,低优先级得等到高优先级全部访问完的空闲时间才能抢得访问权。
这两点中, 第一点一定得要,不然无法体现出优先的意思 。
第二点可以根据程序的需要决定。
typedef int Semaphore;
Semaphore mutex = 1, w = 1;
int ReadCnt = 0;
//下面读者和写者进程并发执行
process Reader ( void )
{
while(1)
{
P(mutex);
ReadCnt++;
if(ReadCnt == 1)
P(w);
V(Mutex);
(对数据进行采集操作);
P(mutex);
ReadCnt--;
if(ReadCnt == 0)
V(w);
V(mutex);
}
}
process Writer ( void )
{
while(1);
{
P(w);
{对数据集进行写操作};
V(w);
}
}
对应上面的读者与写者两个队列(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);
}