Search code examples
multithreadingmutexdeadlockcondition-variable

Dead lock in the mutex, condition variable code?


I'm reading the book, Modern Operation Systems by AS TANENBAUM and it gives an example explaining condition variable as below. It looks to me there is a deadlock and not sure what I miss.

Lets assume consumer thread starts first. Right after the_mutex is locked, consumer thread is blocked waiting for the condition variable, condc.

If producer is running at this time, the_mutex will still be locked, because consumer never releases it. So producer will also be blocked.

This looks to me a textbook deadlock issue. Did I miss something here? Thx

#include <stdio.h>
#include <pthread.h>

#define MAX 10000000000         /* Numbers to produce */
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;


void* consumer(void *ptr) {
  int i;

  for (i = 1; i <= MAX; i++) {
    pthread_mutex_lock(&the_mutex); /* lock mutex */

    /*thread is blocked waiting for condc */
    while (buffer == 0) pthread_cond_wait(&condc, &the_mutex);
    buffer = 0;
    pthread_cond_signal(&condp);    
    pthread_mutex_unlock(&the_mutex);
  }
  pthread_exit(0);
}

void* producer(void *ptr) {
  int i;

  for (i = 1; i <= MAX; i++) {
    pthread_mutex_lock(&the_mutex); /* Lock mutex */

    while (buffer != 0) pthread_cond_wait(&condp, &the_mutex);
    buffer = i;
    pthread_cond_signal(&condc);    
    pthread_mutex_unlock(&the_mutex);   
  }
  pthread_exit(0);
}

int main(int argc, char **argv) {
  pthread_t pro, con;

  //Simplified main function, ignores init and destroy for simplicity
  // Create the threads
  pthread_create(&con, NULL, consumer, NULL);
  pthread_create(&pro, NULL, producer, NULL);
}

Solution

  • When you wait on a condition variable, the associated mutex is released for the duration of the wait (that's why you pass the mutex to pthread_cond_wait).

    When pthread_cond_wait returns, the mutex is always locked again.

    Keeping this in mind, you can follow the logic of the example.