Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include #include #include #include #include #include
- bool flag;
- class BoundedBuffer {
- public:
- BoundedBuffer(size_t capacity) : capacity_(capacity) {}
- void put(int item) {
- std::unique_lock lacat(mutex_);
- not_full_cv_.wait(lacat, [&] {return isNotMax(); });
- std::cout << "Am pus elementul: " << item << std::endl;
- this->buffer_.push_back(item);
- not_empty_cv_.notify_one();
- }
- int get() {
- std::unique_lock lacat(mutex_);
- not_empty_cv_.wait(lacat, [&] {return isNotEmpty(); });
- int element = this->buffer_.back();
- std::cout << "Am scos elementul: " << element << std::endl;
- this->buffer_.pop_back();
- not_full_cv_.notify_one();
- return element;
- }
- bool isNotMax()
- {
- return this->buffer_.size() < this->capacity_;
- }
- bool isNotEmpty()
- {
- return this->buffer_.size();
- }
- private:
- std::deque buffer_;
- const size_t capacity_;
- std::mutex mutex_;
- std::condition_variable not_full_cv_;
- std::condition_variable not_empty_cv_;
- };
- void producer(BoundedBuffer& buffer, int num_items) {
- for (int i = 1; i <= num_items; i++)
- buffer.put(i);
- }
- void consumer(BoundedBuffer& buffer, int num_items) {
- for (int i = 1; i <= num_items; i++)
- buffer.get();
- }
- int main() {
- const int capacity = 10;
- const int num_items = 20;
- BoundedBuffer buffer(capacity);
- std::thread producer_thread(producer, std::ref(buffer), num_items);
- std::thread consumer_thread(consumer, std::ref(buffer), num_items);
- producer_thread.join();
- consumer_thread.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment