+ 1

Producer consumer problem

Hi I have a scenario of producer and consumer with bounded buffer (say for example, 3 producers and 2 consumers and capacity to store produced items is 10). Producer consumer can be implemented using mutex and condition variable. This is ok and I am almost clear on this implementation. Now, as it has mutex and mutex is a blocking call, can we have an option to avoid this. Most of the people and articles suggest about the semaphores. I get it that we use two semaphores with signal and wait mechanism. These two semaphores takes care of the empty slots and free slots each. Still queue need to be protected and can be protected using mutex again. So, what is the advantage of semaphores as we still go ahead with blocking calls of mutex again? We excluded condition variables but not mutex by using semaphores. Any thoughts will be of great help. Thanks in advance..!

11th Feb 2025, 5:01 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 odpowiedzi
+ 1
Semaphores minimize mutex contention by preventing unnecessary acquisition attempts. While the queue still requires mutex protection, semaphores ensure that producers do not attempt to add to a full buffer and consumers do not attempt to remove from an empty queue. This results in higher operational efficiency compared to condition variables.
14th Feb 2025, 6:17 AM
MD SHAREK
MD SHAREK - avatar
0
That's my concern aqually. Producer has to produce and put the data into queue. So anyway, queue is to be locked to put produced data . What's the additional need of full semaphore? Same way, consumer need to pop data from queue . Then what's the need for additional semaphore of empty queue?
14th Feb 2025, 8:02 AM
Ketan Lalcheta
Ketan Lalcheta - avatar