Producer Consumer problem using mutex


 
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
 
// Max buffer size user for producing
#define buff_sz 10
 
// buffer index would be the current index
volatile int buff_idx = -1;
// buffer used to produce item
volatile char *buff = NULL;;
 
// Initialization and declaration of muetxt and condition variables
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buff_not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t buff_not_empty = PTHREAD_COND_INITIALIZER;
 
// Consumer thread
void *Consumer()
{
        while(1)
        {
                // Taking lock to avoid race condition
                pthread_mutex_lock(&mutex);
 
                // time to sleep if nothing to consume
                while (buff_idx == -1)
                {
                        // sleeping on condition variable
                        pthread_cond_wait(&buff_not_empty, &mutex);
                }
                // Hey.. we have free index available to produce. Man, it time to produce
                printf("Consumed item from:%d\t", buff_idx--);
 
                // unlock mutex
                pthread_mutex_unlock(&mutex);
 
                // weak up any waiting producer thread as we have just consumed item. So new item can be produced
                pthread_cond_signal(&buff_not_full);
        }
}
 
// Producer
void *Producer()
{
        while(1)
        {
                // Taking lock to avoid race condition
                pthread_mutex_lock(&mutex);
 
                // time to sleep/wait if buffer is full
                while (buff_idx == buff_sz - 1)
                {
                        // sleeping on condition variable
                        pthread_cond_wait(&buff_not_full, &mutex);
                }
 
                // We have empty buffer cell. Put an item into buffer
                buff[++buff_idx] = 'I';
                printf("Produced item at:%d\t", buff_idx);
                // unlock mutex
                pthread_mutex_unlock(&mutex);
 
                // weak up any waiting consumer thread to consume as we have just produced an item
                pthread_cond_signal(&buff_not_empty);
        }
}
 
int main()
{
        pthread_t producer_thread_id, consumer_thread_id;
 
        buff = (char *) malloc(sizeof(char) * buff_sz);
        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;
}



                                                                                                                                                 -> Sachin Birhade

Comments

Popular posts from this blog

STL Questions

Interview questions