12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- #ifndef IMAGEBUFFER_H
- #define IMAGEBUFFER_H
- #include <opencv2/opencv.hpp>
- #include <mutex>
- #include <condition_variable>
- #include <queue>
- template<typename T>
- class ConsumerProducerQueue
- {
- public:
- ConsumerProducerQueue(int mxsz,bool dropFrame) :
- maxSize(mxsz),dropFrame(dropFrame)
- { }
- bool add(T request)
- {
- std::unique_lock<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex);
- while (!isEmpty())
- {
- cpq.pop();
- }
- lock.unlock();
- cond.notify_all();
- }
- private:
- std::condition_variable cond; //条件变量允许通过通知进而实现线程同步
- std::mutex mutex; //提供了多种互斥操作,可以显式避免数据竞争
- std::queue<T> cpq; //容器适配器,它给予程序员队列的功能
- int maxSize;
- bool dropFrame;
- };
- #endif // IMAGEBUFFER_H
|