Producer and Consumer problem Algorithm

  • This is an example of multi-process synchronization problem.
  • This problem can be solved by the condition variables.
  • Two condition variables are taken one for a producer and other for a consumer.

Algorithm for producer and consumer:

pthread_mutex_t lock;
pthread_cond_t empty, fill;

void *producer(void *args)
{
    pthread_mutex_lock(&lock);
    while( buffer_is_fill)
          pthread_cond_wait(&buffer_empty, &lock);
    write_data_to_buffer;
    pthread_cond_signal(&buffer_fill);
    pthread_mutex_unlock(&lock)
}

void *consumer( void *args)
{
   pthread_mutex_lock(&lock)
   while( buffer_empty)
       pthread_cond_wait(&buffer_fill, &lock);
   read_data_from_buffer;
   pthread_cond_signal(&empty);
   pthread_mutex_unlock(&lock);
}

Why Mutex lock is taken:Consider a scenario of two producer:

  • If the first producer(P1) produces the data and calls put_data() function to puts the data at 0th location of buffer but before the index is incremented to 1, it is preempted by another producer(P2).
  • The second producer will produce the data and uses the same old index and put data at buffer[0].
  • Thus the value of producer(P1) is lost.
  • Filling the buffer and incrementing the index is a part of the critical section and hence must be safeguarded against race conditions.
  • Thus both producer and consumer must be locked that it should be mutually exclusive.


Categories: Operating system (OS)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: