#ifndef IMAGEBUFFER_H #define IMAGEBUFFER_H #include #include #include #include template class ConsumerProducerQueue { public: ConsumerProducerQueue(int mxsz,bool dropFrame) : maxSize(mxsz),dropFrame(dropFrame) { } bool add(T request) { std::unique_lock lock(mutex); if(dropFrame && isFull()) { //lock.unlock(); //return false; cpq.pop(); cpq.push(request); cond.notify_all(); return true; } else { cond.wait(lock, [this]() { return !isFull(); }); cpq.push(request); //lock.unlock(); cond.notify_all(); return true; } } void consume(T &request) { std::unique_lock lock(mutex); cond.wait(lock, [this]() { return !isEmpty(); }); request = cpq.front(); cpq.pop(); //lock.unlock(); cond.notify_all(); } bool isFull() const { return cpq.size() >= maxSize; } bool isEmpty() const { return cpq.size() == 0; } int length() const { return cpq.size(); } void clear() { std::unique_lock lock(mutex); while (!isEmpty()) { cpq.pop(); } lock.unlock(); cond.notify_all(); } private: std::condition_variable cond; //条件变量允许通过通知进而实现线程同步 std::mutex mutex; //提供了多种互斥操作,可以显式避免数据竞争 std::queue cpq; //容器适配器,它给予程序员队列的功能 int maxSize; bool dropFrame; }; #endif // IMAGEBUFFER_H