Producer Consumer Problem : Operating System : Semaphores

    


    A very well known synchronization problem in the study of Operating System is the Producer-Consumer Problem. Any new synchronization technique should be able to solve this problem. This problem may be solved using one of the software synchronization tools called - Semaphore. 

Problem There is a shared buffer, a Producer and a Consumer. The buffer is used for putting any new item produced by the Producer. Consumer consumes items from the buffer. Now, the problem is - as the buffer is shared and two processes are accessing the buffer simultaneously, there may be inconsistency of data. So we need a synchronization method , such that, the storing of item within buffer by Producer, and the accessing of items from buffer by Consumer is synchronized, so that buffer data remains consistent. To achieve this we must ensure that -

  •     Only one process at a time should access the buffer.
  •     Producer can't produce if buffer is full.
  •     Consumer can't consume if buffer is empty.

Suppose, buffer size is N.



Solution using Semaphores:

 We will use three semaphores for the three requirements - 

  1. mutex - for providing mutual exclusion on the buffer
  2. full - counting semaphore to keep count of full slots of buffer
  3. empty - counting semaphore to keep count of empty buffer slots.

mutex = 1, full = 0, empty = N ----> in the beginning.

    Now, Producer will intend to produce item if at least one empty slot is available. And if it is true, then it will check whether Consumer is consuming or not, if yes then Producer must wait for Consumer to release the buffer. 

    Similarly, Consumer will intend to consume if there is at least one full slot in buffer and Producer is not producing. Otherwise it will wait. 

    Now let's see the Pseudo-code for Producer and Consumer process, with respect to the above discussed solution.

PRODUCER PROCESS:

while(true){
  wait(empty)
  wait(mutex)
  // PRODUCE ITEM AND ADD TO BUFFER
  signal(mutex)
  signal(full)
}

CONSUMER PROCESS:

while(true){
  wait(full)
  wait(mutex)
  // CONSUME AN ITEM FROM BUFFER
  signal(mutex)
  signal(empty)
}

Hope this post is helpful for you. Thank you for reading till the end. Have a good day. Bye.

Imon Raj

Software, Web & Android Developer

My Skills:

Popular posts from this blog

Which one is better ? GeeksForGeeks or Leetcode ? How many questions to solve ?

Random Gradient Generator With CSS and Javascript