Header Ads

Producer Consumer Problem

In computing, the producer-consumer problem[1][2] (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.


Solution:  


#include< stdio.h>
#include< pthread.h>
#include< semaphore.h>
void *producer(void *arg);
void *consumer(void *arg);
char buff[20];
sem_t full,empty;
int main()
{
        pthread_t pid,cid;
        sem_init(&empty,0,1);
        sem_init(&full,0,0);
        pthread_create(&pid,NULL,producer,NULL);
        pthread_create(&cid,NULL,consumer,NULL);
        pthread_join(pid,NULL);
        pthread_join(cid,NULL);
}
void *producer(void *arg)
{
        int run=1;
        while(run)
        {
                sem_wait(&empty);
                printf("\n Enter into buffer");
                scanf("%s",buff);
                run=0;
                sem_post(&full);
        }
        return NULL;
}
void *consumer(void *arg)
{
        int run=1;
        while(run)
        {
                sem_wait(&full);
                printf("\n item consume");
        }
        return NULL;
}






Powered by Blogger.