I want to know how to solve the producer/consumer problem but using 2 differents consumers and I also need to know how to solve it using strict alternation.
I made the following algorithm for 1 producer and 1 consumer
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
}
}
Using that kind of “pseudo-code” I want to know to to solve the same problem(if the last was OK) with 2 consumers.
You can use the router pattern on small scale in both cases:
(source: enterpriseintegrationpatterns.com)
Basically after the queue you place special artifical consumer (router, just one). If you have two competing consumers, just put each received message randomly either in
outQueue1oroutQueue2.In case of strict alternation, the router remember which queue was used last time and sends to the second one.
If you don’t want to introduce extra step, you need some sort of synchronization. In first case both consumers are competing for the same lock that they obtain randomly. The latter case is more complicated and will require more advanced synchronization so that both consumers are woken up alternatively.