consumer/producer in c++

前端 未结 4 1697
灰色年华
灰色年华 2020-12-15 14:18

This is a classic c/p problem where some threads produce data while other read the data. Both the producer and consumers are sharing a const sized buffer. If the buffer is e

4条回答
  •  情话喂你
    2020-12-15 14:51

    Your queue is not synchronized, so multiple producers could call push_back at the same time, or at the same time the consumer is calling pop_front ... this will break.

    The simple approach to making this work is to use a thread-safe queue, which can be a wrapper around the std::queue you already have, plus a mutex.

    You can start by adding a mutex, and locking/unlocking it around each call you forward to std::queue - for a single consumer that should be sufficient, for multiple consumers you'd need to fuse front() and pop_front() into a single synchronized call.

    To let the consumer block while the queue is empty, you can add a condition variable to your wrapper.

    That should be enough that you can find the answer online - sample code below.


    template  class SynchronizedQueue
    {
        std::queue queue_;
        std::mutex mutex_;
        std::condition_variable condvar_;
    
        typedef std::lock_guard lock;
        typedef std::unique_lock ulock;
    
    public:
        void push(T const &val)
        {
            lock l(mutex_); // prevents multiple pushes corrupting queue_
            bool wake = queue_.empty(); // we may need to wake consumer
            queue_.push(val);
            if (wake) condvar_.notify_one();
        }
    
        T pop()
        {
            ulock u(mutex_);
            while (queue_.empty())
                condvar_.wait(u);
            // now queue_ is non-empty and we still have the lock
            T retval = queue_.front();
            queue_.pop();
            return retval;
        }
    };
    

    Replace std::mutex et al with whatever primitives your "Thread.h" gives you.

提交回复
热议问题