Monday, October 10

SEMAPHORES TO IMPLEMENT PRODUCER CONSUMER PROBLEM

#include<sys/sem.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<sys/ipc.h>
void up(int);
void down(int);
union value
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminto *_buf;
}
main()
{
int mutex,full,empty,pid,i,key,j,k;
union value arg;
key=ftok("",'a');
mutex=semget(key,1,0660|IPC_CREAT);
arg.val=0;
semctl(full,0,SETVAL,arg);
key=ftok("",'c');
empty=semget(key,1,0660|IPC_CREAT);
arg.val=4;
semctl(empty,0,SETVAL,arg);
pid=fork();
switch(pid)
{
case -1:
printf("Error");
case 0:
sleep(13);
printf("\n");
printf("Consumer consuming items\n");
for(i=0;i<5;i++)
{
down(full);
down(mutex);
for(j=4-i;j>=1;j--)
printf("*");
for(k=0;k<=i;k++)
printf("_");
printf("\n");
fflush(stdout);
up(mutex);
up(empty);
sleep(1);
}
printf("Buffer empty\n");
break;
default:
printf("Producer producing items\n");
for(i=0;i<5;i++)
{
down(full);
down(mutex);
//printf("producer is producing %dth item\n",i);
for(j=4-i;j>=1;j--)
printf("_");
for(k=0;k<=i;k++)
printf("*");
printf("\n");
fflush(stdout);
up(mutex);
up(full);
sleep(1);
}
printf("Buffer full\n");
break;
}}
void down(int id)
{
struct sembuf sb={0,-1,0};
semop(id,&sb,1);
}
void up(int id)
{
struct sembuf sb={0,1,0};
semop(id,&sb,1);
}

2 comments :

Unknown said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Good article. but those are new in thread programming cant understand smoothly. so can you please make it simpler for those who are studying
first time with producer consumer concept.

Anonymous said... Best Blogger Tips [Reply to comment] Best Blogger Templates

Thank for your code..but i am new in yacc programing ... I diidnt got the mean of this statement :
num1:num1 num{$$ = $1*10 + $2;}

Post a Comment