Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 生产者/消费者问题的求解算法_Algorithm_Concurrency_Operating System - Fatal编程技术网

Algorithm 生产者/消费者问题的求解算法

Algorithm 生产者/消费者问题的求解算法,algorithm,concurrency,operating-system,Algorithm,Concurrency,Operating System,我想知道如何解决生产者/消费者问题,但使用2个不同的消费者,我还需要知道如何使用严格的交替解决它 我为一个生产者和一个消费者做了以下算法 producer() { while(true) { if i == N //full buffer turn = 1 while turn <> 0 { // nothing } produceitem(&item)

我想知道如何解决生产者/消费者问题,但使用2个不同的消费者,我还需要知道如何使用严格的交替解决它

我为一个生产者和一个消费者做了以下算法

producer()
{
   while(true)
   {
       if i == N //full buffer
          turn = 1
       while turn <> 0
       {
           // nothing
       }
       produceitem(&item)//produce the item
       insertitem(item, buffer)//insert the item in the buffer
       turn = 1
       //process zone
   }
}

consumer()
{
   while(true)
   {
       if i == 0 //empty buffer
          turn = 0
       while turn <> 1
       {
           // nothing
       }
       consumeitem(&item)
       deleteitem(buffer)//erase the item from buffer
       turn = 0
       //process zone
   }
}
producer()
{
while(true)
{
如果i==N//缓冲区已满
圈数=1
当你转身时
{
//没什么
}
produceitem(&item)//生成项目
insertitem(item,buffer)//在缓冲区中插入项
圈数=1
//工艺区
}
}
消费者()
{
while(true)
{
如果i==0//空缓冲区
转动=0
而第1回合
{
//没什么
}
消费项(&item)
deleteitem(buffer)//从缓冲区中删除该项
转动=0
//工艺区
}
}
我想知道,使用这种“伪代码”可以解决两个消费者的相同问题(如果最后一个还可以的话)。

在这两种情况下,您都可以小规模使用:


(来源:)

基本上,在队列之后,您放置特殊的人工消费者(路由器,只有一个)。如果您有两个相互竞争的消费者,只需将收到的每条消息随机放入
outQueue1
outQueue2

在严格交替的情况下,路由器记住上次使用的队列并发送到第二个队列


如果不想引入额外的步骤,则需要某种同步。在第一种情况下,两个消费者都在竞争随机获得的同一个锁。后一种情况更复杂,需要更高级的同步,以便交替唤醒两个使用者。

第二个函数肯定应该命名为
consumer()