In: Computer Science
select one of the below process synchronization problem and describe the problem and its solution
1) producer - consumer problem
2) the dining - philosophers problem
3) reader - writer problem
4) sleeping barber problem
Selecting producer consumer problem for answering from these synchronization problem
1) Producer - consumer problem
Producer consumer problem is a classic synchronization problem. The problem can be solved by using semaphores.
Problem statement
We have a buffer of fixed size. A producer produces an item and place it on the buffer. A consumer takes the item from the buffer and consumes it. We are in need to ensure that when the producer places an item the consumer should not consume any item at the same time. The buffer is the critical section in this problem.
To solve this two counting semaphores are used, full and empty. Full semaphore keep the number of items in buffer at any given time and empty semaphore keeps track of the number of unoccupied slots.
Semaphore
Semaphore S is an integer that can be accessed only through two standard operations: wait() and signal().
The wait() operation reduces the value by 1band signal() operation increases the value of semaphore by 1. It is depicted as follows in c program
wait(S)
{
whole(S<=0) ;
S--;
}
signal(S)
{
S++;
}
Semaphores are of two types, binary semaphore and counting semaphore.
Binary semaphore: It is smiliar to mutex lock and it can only have two values 0 and 1.wiyh value intialized to 1. It is used to implement the critical section problem with multiple processes.
Counting semaphore: It's value can range over a unrestricted domain. It is used to control access to a resource that has multiple instances.
Initilization of semaphores
mutex = 1
Full = 0 // Initially all slots are empty this full slots are zero
Empty = n // Initially all slots are empty
Solution for producer
do
{ // placing an item
wait(empty);
wait(mutex);
//place in buffer
signal(mutex);
signal(full);
}
while(true)
When producer produces an item the value of empty will reduced by 1 as an item occupy the empty space. The value of mutex is reduced to prevent the consumer from accessing the item in buffer bufffer. After the item is placed in buffer. The value of full and mutex is increased by 1. As now the item is available and it can be accessed by consumer.
Solution for consumer
do
{
wait(full) ;
wait(mutex) ; // remove item from buffer
signal(mutex) ;
signal(buffer) ; //consumes items
} while (true)
As the consumer is removing an item from buffer the value of full and mutex is also reduced by1, to prevent the producer from accessing the buffer. After that the value of empty is increased by 1 after the consumer consumes the item also the mutex is also increased by 1 as now producer can access the bufffer