Advertisement
den4ik2003

Untitled

Jun 29th, 2023
1,041
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include "tagged_semaphore.hpp"
  4.  
  5. #include <deque>
  6.  
  7. // Bounded Blocking Multi-Producer/Multi-Consumer (MPMC) Queue
  8.  
  9. template <typename T>
  10. class BoundedBlockingQueue {
  11.  public:
  12.   explicit BoundedBlockingQueue(size_t capacity)
  13.       : capacity_(capacity),
  14.         lower_semaphore_(0),
  15.         upper_semaphore_(capacity),
  16.         like_mutex_(1) {
  17.   }
  18.  
  19.   void Put(T value) {
  20.     auto token(std::move(upper_semaphore_.Acquire()));
  21.  
  22.     auto lock(std::move(like_mutex_.Acquire()));
  23.     buffer_.push_back(std::move(value));
  24.     like_mutex_.Release(std::move(lock));  // нужен ли тут мув?
  25.  
  26.     lower_semaphore_.Release(std::move(token));
  27.   }
  28.  
  29.   T Take() {
  30.     auto token(std::move(lower_semaphore_.Acquire()));
  31.  
  32.     auto lock(std::move(like_mutex_.Acquire()));
  33.     T front(std::move(buffer_.front()));
  34.     buffer_.pop_front();
  35.     like_mutex_.Release(std::move(lock));
  36.  
  37.     upper_semaphore_.Release(std::move(token));
  38.     return front;
  39.   }
  40.  
  41.  private:
  42.   // Tags
  43.   struct TagLikeMutex {};
  44.  
  45.   struct TagLowerUpper {};
  46.  
  47.  private:
  48.   size_t capacity_;
  49.   std::deque<T> buffer_;
  50.   TaggedSemaphore<TagLowerUpper> lower_semaphore_;
  51.   TaggedSemaphore<TagLowerUpper> upper_semaphore_;
  52.   TaggedSemaphore<TagLikeMutex> like_mutex_;
  53. };
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement