gpt4 book ai didi

c - pthread_mutex_lock 导致死锁

转载 作者:太空狗 更新时间:2023-10-29 17:16:29 28 4
gpt4 key购买 nike

我正在使用上面的代码使用 2 个线程递增计数器,这两个线程独立地获取 mut 锁和递增计数器。线程进入此函数后,我面临死锁。

 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;
}

谁能告诉我到底哪里出错了?

最佳答案

您正在尝试锁定互斥体 max 次,然后递增 counter 并释放一次。

尝试:

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

关于c - pthread_mutex_lock 导致死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12650595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com