Producer Consumer Problem

Producer Consumer Problem | Producer Consumer Problem C++

The producer consumer problem (bounded buffer problem) is a great case of a multi-process synchronization issue. The issue portrays two procedures, the producer and the consumer, which share a typical, settled size buffer utilized as a line.
The producer's activity is to create data, place it into the buffer, and begin once more. In the meantime, the consumer is devouring the data (for example expelling it from the buffer), one piece at any given moment.


producer consumer problem
Producer Consumer Problem


Problem: To ensure that the producer won't attempt to include data into the buffer if it's full and that the consumer won't endeavor to expel data from an empty buffer.
Solution: The producer is to either rest or dispose of data if the buffer is full. Whenever the consumer expels a thing from the buffer, it informs the producer, who begins to fill the buffer once more. Similarly, the consumer can rest in the event that it observes the buffer to be empty. Whenever the producer places data into the buffer, it awakens the sleeping consumer. An insufficient solution could result in a halt where the two procedures are holding on to be stirred.


Producer Consumer Problem C++ Program


#include<iostream>
#include<cstdlib>
#include<ctime>
#define size 50
using namespace std;
int in=0,out=0;
int s[size] = {};
void consumer()
{

   if(in<=out)
       return;
   else
   {
  int a=s[out];
       cout<<a<<" is consumed"<<endl;
       s[out]=0;
       out++;
}}
void producer(int n)
{
   if(in>size)
       return;
   else
   {
       out=0;
       s[in]=n;
       cout<<n<<" is produced"<<endl;
       in++;
   }
}
int main()
{
   int a;
   srand(time(NULL));
   int r[12]={1,1,2,1,1,2,2,2,1,1,2,2};
   int values[12];
   for(int i=0;i<12;i++)
   {
       values[i] = rand() % 10 + 1;
   }
   for(int i=0;i<12;i++)
   {   a=r[i];
       switch(a)
       {
           case 1:producer(values[i]);
           break;
           case 2:consumer();
           break;
           default:break;
       } }}
OUTPUT :
9 is produced
9 is produced
9 is consumed
5 is produced
1 is produced
9 is consumed
5 is consumed
1 is consumed
4 is produced
10 is produced
4 is consumed
10 is consumed

You must be also searching for these programming languages : 

tags: producer consumer problem, producer consumer problem C++, poducer consumer problem in c, producer consumer problem in OS.

Post a Comment

Previous Post Next Post