Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. template <typename _Tp>
  2. class SharedQueue
  3. {
  4. public:
  5. explicit SharedQueue(bool isBlocking = true) : isBlocking_(isBlocking) {}
  6.  
  7. virtual ~SharedQueue() {}
  8.  
  9. virtual const _Tp& front()
  10. {
  11. std::unique_lock<std::mutex> mlock(mtx_);
  12.  
  13. // if this is a blocking queue, wait to be notified when when a new object is added
  14. if (isBlocking_)
  15. {
  16. while (queue_.empty())
  17. {
  18. cv_.wait(mlock);
  19. }
  20. }
  21.  
  22. return queue_.front();
  23. }
  24.  
  25. virtual bool empty() const
  26. {
  27. std::unique_lock<std::mutex> mlock(mtx_);
  28.  
  29. return queue_.empty();
  30. }
  31.  
  32. virtual size_t size() const
  33. {
  34. std::unique_lock<std::mutex> mlock(mtx_);
  35.  
  36. return queue_.size();
  37. }
  38.  
  39. virtual void push(const _Tp& value)
  40. {
  41. std::unique_lock<std::mutex> mlock(mtx_);
  42.  
  43. queue_.push(value);
  44.  
  45. if (isBlocking_)
  46. {
  47. if (queue_.size() == 1)
  48. {
  49. cv_.notify_all();
  50. }
  51. }
  52. }
  53.  
  54. virtual void push(_Tp&& value)
  55. {
  56. {
  57. std::unique_lock<std::mutex> mlock(mtx_);
  58.  
  59. queue_.push(std::move(value));
  60.  
  61. if (isBlocking_)
  62. {
  63. if (queue_.size() == 1)
  64. {
  65. cv_.notify_all();
  66. }
  67. }
  68. }
  69. }
  70.  
  71. template <typename... _Args>
  72. void emplace(_Args&&... __args)
  73. {
  74. {
  75. std::unique_lock<std::mutex> mlock(mtx_);
  76.  
  77. queue_.emplace(std::forward<_Args>(__args)...);
  78.  
  79. if (isBlocking_)
  80. {
  81. if (queue_.size() == 1)
  82. {
  83. cv_.notify_all();
  84. }
  85. }
  86. }
  87. }
  88.  
  89. virtual void pop()
  90. {
  91. std::unique_lock<std::mutex> mlock(mtx_);
  92.  
  93. if (!queue_.empty())
  94. {
  95. queue_.pop();
  96. }
  97. }
  98.  
  99. private:
  100. bool isBlocking_;
  101.  
  102. mutable std::mutex mtx_;
  103.  
  104. mutable std::condition_variable cv_;
  105.  
  106. std::queue<_Tp> queue_;
  107. };
  108.  
  109. std::queue<std::unique_ptr<int32_t>> q1;
  110.  
  111. SharedQueue<std::unique_ptr<int32_t>> q2;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement