6

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?

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Shehbaz Jaffer
  • 1,944
  • 8
  • 23
  • 30

4 Answers4

13

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; 
Mat
  • 202,337
  • 40
  • 393
  • 406
3

That is maybe what you tried to do:

int max = MAX_COUNTER_VALUE;
int iter;
int counter;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

void *increment_counter(void *counter_addr)


{

  pthread_mutex_lock(&mut);    
  for(iter=0;iter< max ;iter++)  
       counter++;
  pthread_mutex_unlock(&mut);
  return NULL; 
}
  • 2 or more threads share only global scope data or data located on the heap(malloc).
  • 2 or more threads do not share variables defined on the stack this data is unique to each thread and there is no need to lock it.

You are welcomed to read in the answers what is shared and what is not shared etc.

0x90
  • 39,472
  • 36
  • 165
  • 245
0

As a principle, the same thread should not lock a mutex more than once and that's what happened here.

lang2
  • 11,433
  • 18
  • 83
  • 133
0

lock initialization is very important. If you don't initialize your locks to the right value your code breaks. One method for initializing your lock is the following:

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

Also you can do this task dynamically by using the following code:

int rc = pthread_mutex_init(&lock, NULL);
assert(rc == 0); // always check success!

Beside lock initialization, you should check for the return code of pthread_mutex_lock to see if it fails or not as if it fails, multiple thread can enter the critical section. For this purpose, you can use a code similar to this which checks for the return code of pthread_mutex_lock:

// Use this to keep your code clean but check for failures
// Only use if exiting program is OK upon failure
void Pthread_mutex_lock(pthread_mutex_t *mutex) {
int rc = pthread_mutex_lock(mutex);
assert(rc == 0);
}
Mona Jalal
  • 34,860
  • 64
  • 239
  • 408