|
|
|
Producer and Consumer
#include #include int mutex=1,full=0,empty=3,x=0; void main() { int n; void producer(); void consumer(); int wait(int); int signal(int); clrscr(); printf("list of choices :\n1.producer \n2.consumer \n3.exit"); while(1) { printf("\n\n enter the choice:"); scanf("%d",&n); switch(n) { case 1: if((mutex==1)&&empty!=0) producer(); else printf("\n buffer is full"); break; case 2: if((mutex==1)&&full!=0) consumer(); else printf("\n buffer is empty"); break; case 3: exit(0); break; } }
} 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("\n producer produces the item %d:",x); mutex=signal(mutex); } void consumer() { mutex=wait(mutex); full=wait(full); empty=signal(empty); printf("\n consumer consumes an item %d:",x); x--; mutex=signal(mutex); }
OUTPUT:
enter the choice:1 producer produces the item 3:
enter the choice:1 buffer is full
enter the choice:2 consumer consumes an item 3:
enter the choice:2 consumer consumes an item 2:
enter the choice:2 consumer consumes an item 1:
enter the choice:2 buffer is empty
enter the choice:3
|
No responses found. Be the first to respond and make money from revenue sharing program.
|