Producer-Consumer Problem Using Semphore

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

#define Buffer_Limit 10

int Buffer_Index_Value = -1;
char *Buffer_Queue;
sem_t mutex,empty_count,fill_count;

 void *Consumer()
{
      while(1)
      {
   sem_wait(&fill_count);
   sem_wait(&mutex);
   printf("Consumer:%d\t", Buffer_Index_Value--);       
   sem_post(&mutex);
   sem_post(&empty_count); 
 
      }   
}

void *Producer()
{   
      while(1)
      {
    sem_wait(&empty_count);
            sem_wait(&mutex);
            Buffer_Queue[++Buffer_Index_Value] = '@';
            printf("Producer:%d\t", Buffer_Index_Value);
    sem_post(&mutex);
    sem_post(&fill_count);
      }   
}

int main()
{   
      pthread_t producer_thread_id, consumer_thread_id;

      sem_init(&mutex,0,1); /*Binary Semaphore*/

      sem_init(&fill_count,0,0);
      sem_init(&empty_count,0,Buffer_Limit);

      Buffer_Queue = (char *) malloc(sizeof(char) * Buffer_Limit);           
      pthread_create(&producer_thread_id, NULL, Producer, NULL);
      pthread_create(&consumer_thread_id, NULL, Consumer, NULL);
      pthread_join(producer_thread_id, NULL);
      pthread_join(consumer_thread_id, NULL);
      return 0;
}

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Adapter Design Pattern