0

I already have a design for my Producer Consumer problem with restrictions.

struct data{
    int id;
    int value;
};

std::list<struct data> g_DataQ;

class Consumer{
    void process_data(){
        struct data my_data = g_DataQ.pop_front();
        if(my_data.id == 0){
          //Consumer 0
        }else if(my_data.id == 1){
          //Consumer 1
        }
        //Process Data
    }
};

void consume(struct data pData){
    g_DataQ.push_back(pData);
}

Description:

Producer is calling "consume" function. And there can be multiple producer/consumer. That data to be consumed by current Consumer is determined by data.id. For every consumer we instantiate a class Consumer. But there is only one consume function.

Restrictions that I have:

  1. "consume" function has to be global.
  2. There can be multiple Producer/Consumer

My main concern is having the global g_DataQ. One way to resolve this is having a list of list where first dimension handles which consumer it belongs to.

My query can it be done without making the Q global?

Thanks in advance.

Rachit Agrawal
  • 3,203
  • 10
  • 32
  • 56
  • @Thomas No, he's asking a very specific question. – Mast Aug 25 '15 at 09:28
  • `std::list` is not guaranteed to be thread-safe, so that might cause problems here. The `id` of your `data` struct could be changed to an enum to have a better overview about what is used where. You could make your global `Consumer` class singleton and move the list inside the class. If needed this would also move the consume function inside and call `Consumer::consume()`. You might even skip the `ìnstance()` function and only provide `consume()` to be callable from the outside. – Simon Kraemer Aug 25 '15 at 09:28
  • @Mast `I want to know what could be a better design for this?` is not very specific... But the second question is, you're right :) – Thomas Ayoub Aug 25 '15 at 09:29
  • @Thomas I am only looking an answer for second question. Thanks for pointing that out. – Rachit Agrawal Aug 25 '15 at 10:00
  • If you declare your consumers as singleton, each would hold the list it is responsible of. If you want to reuse the same Consumer class for multiple consumers this would be the same, but w/o the singleton pattern. You would have to create globally available, static instances. – Simon Kraemer Aug 25 '15 at 10:06

0 Answers0