Producer-Consumer Problem in C

Here you will find out about maker buyer issue in C.

Maker buyer issue is otherwise called a limited cushion issue. In this issue, we have two procedures, maker and shopper, who offer fixed size support. Maker work is to deliver information or things and put in the cushion.

Purchaser work is to expel information from the cushion and devour it. We need to ensure that the maker doesn’t deliver information when a cushion is full and the shopper doesn’t expel information when the cradle is vacant.

The maker ought to rest when support is full. Next time when customer expels information it advises the maker and maker starts delivering information once more.

The customer ought to rest when the cradle is unfilled. Next time when maker includes information it advises the purchaser and customer starts devouring information. This arrangement can be accomplished by utilizing semaphores.

Producer-Consumer Problem in C

#include<stdio.h>
#include<stdlib.h>
 
int mutex=1,full=0,empty=3,x=0;
 
int main()
{
	int n;
	void producer();
	void consumer();
	int wait(int);
	int signal(int);
	printf("\n1.Producer\n2.Consumer\n3.Exit");
	while(1)
	{
		printf("\nEnter your choice:");
		scanf("%d",&n);
		switch(n)
		{
			case 1:	if((mutex==1)&&(empty!=0))
						producer();
					else
						printf("Buffer is full!!");
					break;
			case 2:	if((mutex==1)&&(full!=0))
						consumer();
					else
						printf("Buffer is empty!!");
					break;
			case 3:
					exit(0);
					break;
		}
	}
	
	return 0;
}
 
int wait(int s)
{
	return (--s);
}
 
int signal(int s)
{
	return(++s);
}
 
void producer()
{
	mutex=wait(mutex);
	full=signal(full);
	empty=wait(empty);
	x++;
	printf("\nProducer produces the item %d",x);
	mutex=signal(mutex);
}
 
void consumer()
{
	mutex=wait(mutex);
	full=wait(full);
	empty=signal(empty);
	printf("\nConsumer consumes item %d",x);
	x--;
	mutex=signal(mutex);
}

Output

1.Producer
2.Consumer
3.Exit
Enter your choice:1

Producer produces the item 1
Enter your choice:2

Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1

Producer produces the item 1
Enter your choice:1

Producer produces the item 2
Enter your choice:1

Producer produces the item 3
Enter your choice:1
Buffer is full!!
Enter your choice:3

The following is the program to execute this issue.

Leave a Comment