Condition variable, Solution of Producer consumer problem using threads, mutex

Condition variable: Condition variables are used for blocking threads if a particular condition is not met. Condition variable is always used with a mutex. Condition variables do not have a memory.

Here are the calls in Pthreads for condition variables:

  • Pthread_cond_init: It is used for creating a condition variable.
  • Pthread_cond_destroy: It is used for destroying a condition variable.
  • Pthread_cond_signal: It is used for signaling another thread and to wake up the thread.
  • Pthread_cond_broadcast: It is used for signaling multiple threads and to wake up all the threads.
  • Pthread_cond_wait: It is used for making a thread wait for a signal.

Solution of Producer consumer problem using threads, mutex and condition variables:

When buffer is filled up by producer, it waits for consumer to remove the item and when the consumer has removed an item, it waits for producer to create the item.

#include <stdio.h>
#include <pthread.h>
#define MAX 1000000000
pthread_mutex_t mutex;
pthread_cond_t conditionc, conditonp;
int buffer = 0;
void *producer(void *ptr)
{ int i;
for (i= 1 ; i <= MAX; i++) {
while (buffer != 0) pthread_cond_wait(&conditionp, &mutex);
buffer = i;
void *consumer(void *ptr)
{ inti;
for (i = 1 ; i <= MAX; i++) {
while (buffer ==0 ) pthread_cond_wait(&conditionc, &mutex);
buffer = 0;
int main(int argc, char **argv)
pthread_t prod, cons;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&conditionc, 0);
pthread_cond_init(&conditionp, 0);
pthread_create(&cons, 0, consumer, 0);
pthread_create(&prod, 0, producer, 0);
pthread_join(prod, 0);
pthread_join(cons, 0);
pthread_cond_destroy(&condiitonp );

Leave a Reply