2012-11-02 82 views
0

我想知道如何解決生產者/消費者問題,但使用2個不同的消費者,我也需要知道如何使用嚴格的交替來解決它。解決生產者/消費者問題的算法

我做了如下算法1個生產者和1名消費者

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

使用那種「僞代碼」我想知道,以解決同樣的問題(如果最後是OK)2消費者。

+0

第二個函數肯定應該命名爲'consumer()'。 –

回答

2

您可以在這兩種情況下,小規模使用router pattern

Router http://www.enterpriseintegrationpatterns.com/img/MessageRouter.gif

基本上隊列後,你把特殊的人工消費(路由器,只有一個)。如果您有兩個競爭消費者,只需將每個收到的消息隨機地放入outQueue1outQueue2

如果發生嚴格交替,路由器會記住上次使用哪個隊列併發送給第二個隊列。

如果您不想引入額外的步驟,則需要某種同步。在第一種情況下,兩個消費者都在爭奪他們隨機獲得的同一把鎖。後一種情況更爲複雜,需要更高級的同步,這樣兩個消費者才能被選擇性地喚醒。