... continued
This lesson explains implementing a bounded buffer using the Semaphore class.
We'll cover the following
Semaphore Implementation
We can also implement the bounded buffer problem using a semaphore. Let's revisit the Semaphore
's constructor. It takes in the initial number of permits and the maximum number of permits. We can use two semaphores, one semConsumer
and the other semProducer
. The trick is to initialize semProducer
semaphore with a maximum number of permits equal to the size of the buffer and set all permits as available. Each permit allows a producer thread to enqueue an item in the buffer. Since the number of permits is equal to the size of the buffer, the producer threads can only enqueue items equal to the size of the buffer and then block. However, the semProducer
is only released/incremented by a consumer thread whenever it consumes an item. If there are no consumer threads, the producer threads will block when the buffer becomes full. In case of the consumer threads, when the buffer is empty, we would want to block any consumer threads on a dequeue()
call. This implies that we should initialize the semConsumer
semaphore with a maximum capacity equal to the size of the buffer and set all the permits as currently given out. Let's look at the implementation of enqueue()
method.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.