Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_mutex_lock causes deadlock

I am using the above code to increment a counter using 2 threads, which independently take the mut lock and increment counter. I am facing a deadlock after the threads enter this function.

 pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

 void *increment_counter(void *counter_addr)
{
    int max = MAX_COUNTER_VALUE;
    int iter;
    int counter;

    for(iter=0;iter< max ;iter++)
   // LOCK  
    pthread_mutex_lock(&mut);
    counter++;
    // UNLOCK 
    pthread_mutex_unlock(&mut);
    return NULL; 
}

Could anyone please tell me where exactly am I going wrong?

like image 394
Shehbaz Jaffer Avatar asked Sep 29 '12 06:09

Shehbaz Jaffer


1 Answers

You're trying to lock the mutex max times, then increment counter and release it once.

Try:

for(iter=0;iter< max ;iter++)
{
  // LOCK  
  pthread_mutex_lock(&mut);
  counter++;
  // UNLOCK 
  pthread_mutex_unlock(&mut);
}
return NULL; 
like image 67
Mat Avatar answered Sep 24 '22 08:09

Mat