#include
#include
#define N 5;
typedef int semaphore;
semaphore mutex=1;
semaphore empty=5;
semaphore full=0;
char buffer[5];
int front=0,rear=0;
int wait (semaphore *s)
{
*s=*s-1;
if(*s<0)
{
printf("\n process is blocked");
*s=0;
return 0;
}
return 1;
}
void signal(semaphore *s)
{
*s=*s+1;
if(*s<=0)
{
printf("Process is unblocked");
}
}
void producer(void)
{
char item;
if(wait("Ø"))
{
if(wait(&mutex))
{
printf("Enter the character data:");
scanf(" %c",&item);
buffer[front]=item;
front=(front+1)%5;
signal(&mutex);
signal(&full);
}
}
}
void consumer(void)
{
char item;
if(wait(&full))
{
if(wait(&mutex))
{
item=buffer[rear];
printf("\n consumed item: %c",item);
rear=(rear+1)%5;
signal(&mutex);
signal("Ø");
}
}
}
void view(void)
{
int i;
printf("\n Buffer data:");
printf("\n+---------------------------------+\n");
for(i=0;i<5;i++)
{
printf("| %c",buffer[i]);
}
printf("\n+---------------------------------+");
}
void main()
{
int i,choice,flag=0;
clrscr();
printf("\n 1. Insert item using Producer");
printf("\n 2. Remove item using Consumer");
printf("\n 3. View buffer data");
printf("\n 4. Exit");
do
{
printf("\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: producer();
break;
case 2: consumer();
break;
case 3: view();
break;
case 4: flag=1;
break;
default:printf("\n Please enter correct choice!");
break;
}
}while(flag==0);
}
/****************************OUTPUT************************************
1. Insert item using Producer
2. Remove item using Consumer
3. View buffer data
4. Exit
Enter your choice:1
Enter the character data:A
Enter your choice:1
Enter the character data:B
Enter your choice:1
Enter the character data:C
Enter your choice:1
Enter the character data:D
Enter your choice:1
Enter the character data:E
Enter your choice:3
Buffer data:
+---------------------------------+
| A| B| C| D| E
+---------------------------------+
Enter your choice:2
consumed item: A
Enter your choice:1
Enter the character data:F
Enter your choice:3
Buffer data:
+---------------------------------+
| F| B| C| D| E
+---------------------------------+
Enter your choice:4
*/
0 comments:
Post a Comment