Pthread_mutex_lock causes deadlock

I use the code above to increment the counter using 2 threads, which independently accept the block counter and the counter. I ran into a dead end after threads entered 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; } 

Can someone tell me exactly where I am going wrong?

+6
source share
4 answers

You are trying to lock mutex max times, then increase 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; 
+10
source

It is possible that 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 area data or data located on heap ( malloc ).
  • 2 or more threads are not shared by variables, the data defined in the stack is unique for each thread, and there is no need to block it.

You are invited to read in the answers what is common and what is not common, etc.

+3
source

As a principle, the same thread should not block mutexes more than once and what happened here.

0
source

initialization lock is very important. If you do not initialize your locks to the desired value, your code breaks. One way to initialize your lock is as follows:

 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 

You can also perform this task dynamically using the following code:

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

In addition to initializing the lock, you should check the pthread_mutex_lock return code to see if it will work or not, as if it worked, several threads can enter the critical section. For this, you can use code similar to this that checks the pthread_mutex_lock return code:

 // 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); } 
0
source

Source: https://habr.com/ru/post/926571/


All Articles