Patey

Untitled

Apr 20th, 2023
816
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. #include  #include  #include  #include  #include  #include  
  2. bool flag;
  3.  
  4. class BoundedBuffer {
  5. public:
  6.     BoundedBuffer(size_t capacity) : capacity_(capacity) {}
  7.  
  8.     void put(int item) {
  9.         std::unique_lock lacat(mutex_);
  10.         not_full_cv_.wait(lacat, [&] {return isNotMax(); });
  11.         std::cout << "Am pus elementul: " << item << std::endl;
  12.         this->buffer_.push_back(item);
  13.         not_empty_cv_.notify_one();
  14.     }
  15.  
  16.     int get() {
  17.         std::unique_lock lacat(mutex_);
  18.         not_empty_cv_.wait(lacat, [&] {return isNotEmpty(); });
  19.         int element = this->buffer_.back();
  20.         std::cout << "Am scos elementul: " << element << std::endl;
  21.         this->buffer_.pop_back();
  22.         not_full_cv_.notify_one();
  23.         return element;
  24.     }
  25.  
  26.     bool isNotMax()
  27.     {
  28.         return this->buffer_.size() < this->capacity_;
  29.     }
  30.  
  31.     bool isNotEmpty()
  32.     {
  33.         return this->buffer_.size();
  34.     }
  35.    
  36. private:
  37.     std::deque buffer_;
  38.     const size_t capacity_;
  39.     std::mutex mutex_;
  40.     std::condition_variable not_full_cv_;
  41.     std::condition_variable not_empty_cv_;
  42. };
  43.  
  44. void producer(BoundedBuffer& buffer, int num_items) {
  45.     for (int i = 1; i <= num_items; i++)
  46.         buffer.put(i);
  47.    
  48. }
  49.  
  50. void consumer(BoundedBuffer& buffer, int num_items) {
  51.     for (int i = 1; i <= num_items; i++)
  52.         buffer.get();
  53. }
  54.  
  55. int main() {
  56.     const int capacity = 10;
  57.     const int num_items = 20;
  58.  
  59.     BoundedBuffer buffer(capacity);
  60.  
  61.     std::thread producer_thread(producer, std::ref(buffer), num_items);
  62.     std::thread consumer_thread(consumer, std::ref(buffer), num_items);
  63.  
  64.     producer_thread.join();
  65.     consumer_thread.join();
  66.  
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment