Definition:
Semaphore is simply a variable which is non-negative and shared between threads. This variable is used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment.
Semaphores in Process Synchronization
Semaphore was proposed by
DijkstraĀ in 1965 which is a very significant technique to manage concurrent processes by using a simple integer value, which is known as a semaphore.
Semaphores are of two types:
- Binary Semaphore āThis is also known as mutex lock. It can have only two values ā 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problem with multiple processes.
- Counting Semaphore āIts value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances.
Bounded Buffer Problem
Bounded buffer problem, which is also calledĀ
producer consumer problem, is one of the classic problems of synchronization. Let's start by understanding the problem here, before moving on to the solution and program code.
What is the Problem Statement?
There is a buffer ofĀ nĀ slots and each slot is capable of storing one unit of data. There are two processes running, namely,Ā
producerĀ andĀ
consumer, which are operating on
the buffer.
Here's a Solution
One solution of this problem is to use semaphores. The semaphores which will be used here are:
- m, aĀ binary semaphoreĀ which is used to acquire and release the lock.
- empty, aĀ counting semaphoreĀ whose initial value is the number of slots in the buffer, since, initially all slots are empty.
- full, aĀ counting semaphoreĀ whose initial value isĀ 0.
At any instant, the current value of empty represents the number of empty slots in the buffer and full represents the number of occupied slots in the buffer.