imageBuffer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #ifndef IMAGEBUFFER_H
  2. #define IMAGEBUFFER_H
  3. #include <opencv2/opencv.hpp>
  4. #include <mutex>
  5. #include <condition_variable>
  6. #include <queue>
  7. template<typename T>
  8. class ConsumerProducerQueue
  9. {
  10. public:
  11. ConsumerProducerQueue(int mxsz,bool dropFrame) :
  12. maxSize(mxsz),dropFrame(dropFrame)
  13. { }
  14. bool add(T request)
  15. {
  16. std::unique_lock<std::mutex> lock(mutex);
  17. if(dropFrame && isFull())
  18. {
  19. //lock.unlock();
  20. //return false;
  21. cpq.pop();
  22. cpq.push(request);
  23. cond.notify_all();
  24. return true;
  25. }
  26. else {
  27. cond.wait(lock, [this]() { return !isFull(); });
  28. cpq.push(request);
  29. //lock.unlock();
  30. cond.notify_all();
  31. return true;
  32. }
  33. }
  34. void consume(T &request)
  35. {
  36. std::unique_lock<std::mutex> lock(mutex);
  37. cond.wait(lock, [this]()
  38. { return !isEmpty(); });
  39. request = cpq.front();
  40. cpq.pop();
  41. //lock.unlock();
  42. cond.notify_all();
  43. }
  44. bool isFull() const
  45. {
  46. return cpq.size() >= maxSize;
  47. }
  48. bool isEmpty() const
  49. {
  50. return cpq.size() == 0;
  51. }
  52. int length() const
  53. {
  54. return cpq.size();
  55. }
  56. void clear()
  57. {
  58. std::unique_lock<std::mutex> lock(mutex);
  59. while (!isEmpty())
  60. {
  61. cpq.pop();
  62. }
  63. lock.unlock();
  64. cond.notify_all();
  65. }
  66. private:
  67. std::condition_variable cond; //条件变量允许通过通知进而实现线程同步
  68. std::mutex mutex; //提供了多种互斥操作,可以显式避免数据竞争
  69. std::queue<T> cpq; //容器适配器,它给予程序员队列的功能
  70. int maxSize;
  71. bool dropFrame;
  72. };
  73. #endif // IMAGEBUFFER_H