优先读者/写者问题—操作系统

所谓谁谁优先的问题,我认为主要体现在以下两点中:

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值