mardi 29 décembre 2020

Shared a concurrent queue

How should I instantiate my queue to be shared with all my object instances?

This is my concurrentQueue class

template <typename T>
class concurrentQueue
{
    public:
        concurrentQueue():data_cond(), mut(){};

        concurrentQueue(const concurrentQueue& other):data_cond(), mut(){
            std::lock_guard<std::mutex> lock(other.mut);
            data_queue = other.data_queue;
        };
        virtual ~concurrentQueue(){}; 
        concurrentQueue &operator=(const concurrentQueue &other) = delete;
    [...]

};

I was thinking of using the reference passage for my differents objects. For example

class consumer :
{
    public:
    consumer(const concurrentQueue<std::string>& queue) : myQueue(queue){};
    void execute(){ std::string s{""}; bool t = myQueue.try_and_pop(s); if (t) {std::cout << s << std::endl;}  };
    
};

class producer :
{
    public:
    producer(const concurrentQueue<std::string>& queue) : myQueue(queue){};
    void execute(){ std::string s=string_random(10); myQueue.push(s); std::cout << myQueue.size() << std::endl;  };
     [...]
    
};

int main()
{ 
    concurrentQueue<std::string> queue;
    producer A(std::ref(queue));
    producer A1(std::ref(queue));
    consumer B(std::ref(queue));
    A.execute();
    A1.execute();
    while(!queue.isEmpty)
     B.execute();
     
    exit
}

What is the best way?

Aucun commentaire:

Enregistrer un commentaire