Lab 13
Lab 13
Lab Manual
Semaphores are used to control access to the shared buffer. We typically use two types of semaphores:
1. Empty: Tracks how many empty slots are available in the buffer.
2. Full: Tracks how many filled slots are available for consumption.
3. Mutex: Ensures mutual exclusion while accessing the buffer.
Page 2 of 5
#include <iostream>
#include <thread>
#include <queue>
#include <semaphore> // C++20 semaphore support
#include <chrono>
● Semaphore Mechanism: The semaphores ensure that the producer does not overfill the buffer and
that the consumer does not try to consume from an empty buffer.
● Thread Safety: The mutex ensures that only one thread accesses the shared buffer at a time,
preventing race conditions.
● Multiple Producers and Consumers: The code handles multiple producers and consumers
simultaneously by using threads.
This solution assumes that you are using a C++20 compiler that supports the std::semaphore. If you're
using an older version of C++, you can replace std::semaphore with POSIX semaphores (sem_t) or
implement your own counting semaphore using mutexes and condition variables.
Practice Question:
Page 4 of 5
Please write, compile, and execute the provided program, using different input parameters as
outlined in your course. Ensure you submit the output to your instructor.
Q1: Recall Producer-Consumer Problem and answer the following CLO1 [10]
Page 5 of 5