简体   繁体   English

pthread_mutex_lock导致死锁

[英]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. 我使用上面的代码使用2个线程递增一个计数器,它独立地使用mut锁和递增计数器。 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? 谁能告诉我我哪里错了?

You're trying to lock the mutex max times, then increment counter and release it once. 您试图锁定互斥锁max次数,然后递增counter并释放一次。

Try: 尝试:

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

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个或多个线程仅共享位于堆上的全局范围数据或数据( 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. 2个或多个线程不共享在堆栈上定义的变量,这些数据对每个线程都是唯一的,并且不需要锁定它。

You are welcomed to read in the answers what is shared and what is not shared etc. 欢迎您在答案中阅读共享内容和未共享内容等。

作为一个原则,同一个线程不应该多次锁定互斥锁,这就是这里发生的事情。

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. 除了锁定初始化之外,您应该检查pthread_mutex_lock的返回代码以查看它是否失败,就好像它失败一样,多个线程可以进入临界区。 For this purpose, you can use a code similar to this which checks for the return code of pthread_mutex_lock : 为此,您可以使用与此类似的代码来检查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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM