Impemnt Producer Consumer Problem In cpp or c
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
# define BufferSize 3
int mutex=1,full=0,empty=3,x=0;
void *producer();
void *consumer();
int BufferIndex=0;
char *BUFFER;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int wait(int);
int Signal(int);
int main()
{
int n;
pthread_t ptid,ctid;
BUFFER=(char *) malloc(sizeof(char) * BufferSize);
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();
pthread_create(&ptid,NULL,producer,NULL);
pthread_join(ptid,NULL);}
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0)){
//consumer();
pthread_create(&ctid,NULL,consumer,NULL);
pthread_join(ctid,NULL);}
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);
}
Comments
Post a Comment