producer consumer problem in c

producer consumer problem in c is also known as bounded buffer problem.it is a classic example of a multi-process synchronization.it describes the consumer producer, both share a common and fixed-size buffer.Producer work is to produce data and put in the buffer and start again. Consumer work is to remove data from the buffer and consume once at a time.problem have to make sure that producer does not try to produce data when the buffer is full and consumer do not remove data when it is empty.
But situations can arise when the producer produce and try to add a data into a full buffer and consumer may try to consume data from an empty buffer.To achieve synchronization, the producer should block when the buffer is full and the consumer should block when the buffer is empty.

algorithm of producer consumer Problem

ALGORITHM

1: Start  the process

2: declare and define the size of the buffer.

3: take input number of producers and consumers.

4: put the producer job put it in the buffer.

5: the consumer can take job from the buffer.

6: buffer is full the producer is in sleep.

7: buffer is empty then the consumer is in sleep.

8: Stop the process

Producer Consumer Problem in c

#include<stdio.h>
#include<stdlib.h>
void PRODUCER();
void CONSUMER();
int m=1;//mutex
int fl;//full
int em;//empty
int temp=0;
int main()
{
    int ch;
    printf("size of buffer:- ");
    scanf("%d",&em);
    printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");
    while(1)
    {
    	printf("\nYour Choice:- ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1: 
				if((m==1)&&(em!=0))
                	PRODUCER();
                else
                    printf("Buffer Full");
                    break;
            case 2:  
				if((m==1)&&(fl!=0))
                   CONSUMER();
                else
                        printf("Buffer Empty");
                    	break;
            case 3:
                    exit(0);
                    break;
        }
    }
    
    return 0;
}
 
void PRODUCER()
{
    m-=1;
    fl+=1;
    em-=1;
    temp+=1;
    printf("Producer produces: %d\n",temp);
    m+=1;
}
 
void CONSUMER()
{
    m-=1;
    fl-=1;
    em+=1;
    printf("Consumer consumes %d\n",temp);
    temp-=1;
    m+=1;
}

you may also like….

memory management in os

Dining Philosophers Problem in os


 

1.PRODUCER
2.CONSUMER
3.EXIT

Your Choice:- 1
Producer produces: 1

Your Choice:- 2
Consumer consumes 1

Your Choice:- 1
Producer produces: 1

Your Choice:- 2
Consumer consumes 1

Your Choice:- 2
Buffer Empty
Your Choice:- 2
Buffer Empty
Your Choice:- 1
Producer produces: 1

Your Choice:- 1
Producer produces: 2

Your Choice:- 1
Producer produces: 3

Your Choice:- 1
Buffer Full
Your Choice:-
producer consumer problem in c
output

 

Leave a Reply

Your email address will not be published. Required fields are marked *