Saturday 2 July 2016

Producer Consumer Problem using Semaphore (Operating Systems)

Producer Consumer Problem using Semaphore (Operating Systems)

#include<stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

typedef int buffer_item;
#define BUFFER_SIZE 5

sem_t mutex;
sem_t empty;
sem_t full;

buffer_item buffer_data[BUFFER_SIZE];
int no_of_elements=0;

int insert_item(buffer_item obj){

   if(no_of_elements<BUFFER_SIZE){
      buffer_data[no_of_elements++]=obj;
      return 0;
   }
   else
      return -1;  
}

int remove_item(buffer_item *obj){
  
   if(no_of_elements==0)
      return -1;
   else{
      *obj=buffer_data[--no_of_elements];
      return 0;
   } 
}

void *Producer(void *param){
    
   buffer_item obj;
   int i,id,time;
   id=param;

   while(1){
      sem_wait(&empty);
      sem_wait(&mutex);

      time=(rand()%3)+2;
      sleep(time);
      obj=rand()%10+1;

      if(insert_item(obj))
         printf("PRODUCER#%d: Report Error Condition\n",id);
      else
         printf("PRODUCER#%d: Item=%d has successfully been produced\n",id,obj);
      sem_post(&mutex);
      sem_post(&full);
   }
}

void *Consumer(void *param){

   buffer_item obj;
   int i,id,time;
   id=param;

   while(1){
      sem_wait(&full);
      sem_wait(&mutex);

      time=(rand()%3)+2;
      sleep(time);

      if(remove_item(&obj))
         printf("CONSUMER#%d: Report Error Condition\n",id);
      else
         printf("CONSUMER#%d: Item=%d has successfully been consumed\n",id,obj);
     
      sem_post(&mutex);
      sem_post(&empty);
   }
}

int main(int argc,char *argv[]){

   sem_init(&mutex, 2, 1);
   sem_init(&empty, 2, 5);
   sem_init(&full, 2, 0);

   int i,temp,sleep_time,no_of_prod_threads,no_of_cons_threads;
  
   sleep_time=atoi(argv[1]);
   no_of_prod_threads=atoi(argv[2]);
   no_of_cons_threads=atoi(argv[3]);
     
   pthread_t threadID;
   pthread_attr_t attributes;
   pthread_attr_init (&attributes);

   for(i=0;i<no_of_prod_threads;i++)
      pthread_create(&threadID,&attributes,Producer,i+1);
     
   for(i=0;i<no_of_cons_threads;i++)
      pthread_create(&threadID,&attributes,Consumer,i+1);
     
   sleep(sleep_time);
   exit(0);

   return 0;
}


No comments

Post a Comment

Recent Posts