Tuesday, April 26, 2011

Producer-Consumer Problem

A sweet implementation of producer consumer courtesy of anurag mathur

#include<semaphore.h>
#include<stdio.h>
#include<sys/types.h>

sem_t n,mutex,e;
int buf,*Buffer,Count;

void producer()
{
    int i;

    while(1)
    {   
        i=random()%100;
        printf("Producer producing the item: %d\n",i);
        sleep(2);
        printf("The producer produced an item: %d \n",i);       
        sem_wait(&e);
        sem_wait(&mutex);
        Buffer[Count++]=i;
        printf("producer added an item : %d\n",i);
        sem_post(&n);
        sem_post(&mutex);
    }
}
void consumer()
{
    sem_wait(&n);
    while(1)
    {
        sem_wait(&n);       
        sem_wait(&mutex);
        printf("consumer took one item %d\n",Buffer[--Count]);
        sem_post(&e);
        sem_post(&mutex);
        printf("Consumer consuming the item %d \n", Buffer[Count]);
        sleep(2);
        printf("consumer consumed the item %d\n",Buffer[Count]);
    }
}
int main()
{
    pthread_t con,prod;   
    pthread_attr_t *a=NULL;
    sem_init(&n,0,0);
    sem_init(&mutex,0,1);
    printf("Enter the buffer size\n");
    scanf("%d",&buf);
    Buffer= (int *)calloc(buf,sizeof(int));
    sem_init(&e,0,buf);
    int *ptr=NULL;
    pthread_create(&prod,a,&producer,ptr);
    pthread_create(&con,a,&consumer,ptr);
   
    pthread_join(prod,NULL);
    pthread_join(con,NULL);
   
    return 0;
}

No comments:

Post a Comment