threadSafeQueue.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. //
  2. // Created by zx on 2019/12/17.
  3. //
  4. #ifndef SRC_THREADSAFEQUEUE_H
  5. #define SRC_THREADSAFEQUEUE_H
  6. #include <queue>
  7. #include <memory>
  8. #include <mutex>
  9. #include <condition_variable>
  10. template<typename T>
  11. class threadsafe_queue
  12. {
  13. private:
  14. mutable std::mutex mut;
  15. std::queue<T> data_queue;
  16. std::condition_variable data_cond;
  17. public:
  18. threadsafe_queue() {}
  19. threadsafe_queue(threadsafe_queue const& other)
  20. {
  21. std::lock_guard<std::mutex> lk(other.mut);
  22. data_queue = other.data_queue;
  23. }
  24. ~threadsafe_queue()
  25. {
  26. while (!empty())
  27. {
  28. try_pop();
  29. }
  30. }
  31. size_t size()
  32. {
  33. return data_queue.size();
  34. }
  35. void push(T new_value)//��Ӳ���
  36. {
  37. std::lock_guard<std::mutex> lk(mut);
  38. data_queue.push(new_value);
  39. data_cond.notify_one();
  40. }
  41. void wait_and_pop(T& value)//ֱ����Ԫ�ؿ���ɾ��Ϊֹ
  42. {
  43. std::unique_lock<std::mutex> lk(mut);
  44. data_cond.wait(lk, [this] {return !data_queue.empty(); });
  45. value = data_queue.front();
  46. data_queue.pop();
  47. }
  48. std::shared_ptr<T> wait_and_pop()
  49. {
  50. std::unique_lock<std::mutex> lk(mut);
  51. data_cond.wait(lk, [this] {return !data_queue.empty(); });
  52. std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
  53. data_queue.pop();
  54. return res;
  55. }
  56. //ֻ���� �� pop
  57. bool front(T& value)
  58. {
  59. std::lock_guard<std::mutex> lk(mut);
  60. if (data_queue.empty())
  61. return false;
  62. value = data_queue.front();
  63. return true;
  64. }
  65. bool try_pop(T& value)//������û�ж���Ԫ��ֱ�ӷ���
  66. {
  67. std::lock_guard<std::mutex> lk(mut);
  68. if (data_queue.empty())
  69. return false;
  70. value = data_queue.front();
  71. data_queue.pop();
  72. return true;
  73. }
  74. std::shared_ptr<T> try_pop()
  75. {
  76. std::lock_guard<std::mutex> lk(mut);
  77. if (data_queue.empty())
  78. return std::shared_ptr<T>();
  79. std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
  80. data_queue.pop();
  81. return res;
  82. }
  83. bool empty() const
  84. {
  85. std::lock_guard<std::mutex> lk(mut);
  86. return data_queue.empty();
  87. }
  88. void clear()
  89. {
  90. while (!empty()) {
  91. try_pop();
  92. }
  93. }
  94. };
  95. #endif //SRC_THREADSAFEQUEUE_H