Wednesday, January 19, 2011

producer/consumer problem

#include
#include
#include
#include
#include
#include
#include
#include
#define size 10
#define EMPTY 0
#define FULL 1
#define MUTEX 0
////////////////////

void upsem(int sem_id,int snum,struct sembuf * semaphore)
{ semaphore->sem_num=snum;
semaphore->sem_op=1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
///////////////////////////////////
void downsem(int sem_id,int snum,struct sembuf * semaphore)
{ semaphore->sem_num=snum;
semaphore->sem_op=-1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
///////////
void initsem(int sem_id,int sem_num,int val)
{
union semum
{ int val;
struct semid_ds * buf;
unsigned short *array;
}argument;
argument.val=val;
semctl(sem_id,sem_num,SETVAL,argument);
}
////////////////////////
void main()
{ key_t shm_key=1234,sem_key=5678;
int * shm;int item;int i;
int shm_id,sem_id;
struct sembuf semaphore;
printf("\n welcome to pc pgm");
shm_id=shmget(shm_key,size+1,IPC_CREAT|0666);
shm=shmat(shm_id,NULL,0);
sem_id=semget(sem_key,1,IPC_CREAT|0666);
initsem(sem_id,FULL,0);
initsem(sem_id,EMPTY,size);
initsem(sem_id,MUTEX,1);
shm[0]=100;
if(fork()==0)
{


while(1)
{ //consumer
sleep(1);
downsem(sem_id,FULL,&semaphore);
downsem(sem_id,MUTEX,&semaphore);
item=shm[1];
for(i=1;i {shm[i]=shm[i+1];}
shm[0]--;

printf("\n consumer consumes %d ",item);
upsem(sem_id,MUTEX,&semaphore);
upsem(sem_id,EMPTY,&semaphore);
}
}
else
{
while(1)
{//producer)
item=random()%10;
sleep(1);
downsem(sem_id,EMPTY,&semaphore);
downsem(sem_id,MUTEX,&semaphore);
shm[++shm[0]]=item;

printf("\n producer produces %d",item);
upsem(sem_id,MUTEX,&semaphore);
upsem(sem_id,FULL,&semaphore);
}
}
}//end of main

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. header files to be included are
    #include"stdio.h"
    #include"unistd.h"
    #include"sys/types.h"
    #include"sys/sem.h"
    #include"sys/shm.h"
    #include"sys/wait.h"
    #include"fcntl.h"
    #include"sys/ipc.h"

    ReplyDelete
  3. what's the code,without using semaphore

    ReplyDelete