pthread_mutex_lock causes deadlock

c, locking, pthreads

Solution

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; 

Problem

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?

Original source

Related problems