gpt4 book ai didi

linux - 条件变量和rwlock死锁

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:13 25 4
gpt4 key购买 nike

我有一个简单的线程程序,它使用一个条件变量和一个 rwlock。我已经盯着它看了好几个小时,尝试不同的方法。问题是一个或多个线程在一段时间后停止在 rwlock,尽管它没有被锁定以进行写入。也许我错过了关于这些锁如何工作或如何实现的一些信息。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <unistd.h>

//global variables
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_rwlock_t rwlock;
int counter;
int listLength = 1;

void* worker(void* arg){
do {
usleep(200);
printf("Before rwlock\n");
pthread_rwlock_rdlock(&rwlock);
printf("Before mutex\n");
pthread_mutex_lock(&mutex);
printf("Afer mutex\n");
counter++;
//signal the main
if (counter == 5 ||
(listLength < 5 && counter == listLength)){
printf("Signal main\n");
pthread_cond_signal(&cond);
counter = 0;
}
pthread_mutex_unlock(&mutex);
pthread_rwlock_unlock(&rwlock);
} while(listLength != 0);

return NULL;
}


int main(int argc, char* argv[]){
if (argc != 2){
perror("Invalid number of args");
exit(1);
}
//get arguments
int workers = atoi(argv[1]);

//initialize sync vars
pthread_rwlockattr_t attr;
pthread_rwlockattr_setkind_np(&attr,
PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_rwlock_init(&rwlock, &attr);
counter = 0;

//create threads
pthread_t threadArray[workers];
int threadOrder[workers];
for (int i = 0; i < workers; i++){
threadOrder[i] = i;
if (pthread_create(&threadArray[i], NULL,
worker, &threadOrder[i]) != 0){
perror("Cannot create thread");
exit(1);
}
}

while(listLength != 0) {
//wait for signal and lock the list
pthread_mutex_lock(&mutex);
while (pthread_cond_wait(&cond, &mutex) != 0);
pthread_rwlock_wrlock(&rwlock);
printf("In write lock\n");

pthread_mutex_unlock(&mutex);
pthread_rwlock_unlock(&rwlock);
printf("release wrlock\n");
}

//join the threads
for (int i = 0; i < workers; i++){
if (pthread_join(threadArray[i], NULL) !=0){
perror("Cannot join thread");
exit(1);
}
}

//release resources
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_rwlock_destroy(&rwlock);

return 0;
}

最佳答案

看起来这段代码有几个不一致的地方。

  1. 您将 mutexrwlock 一起使用,这意味着所有此类线程始终处于锁定状态。如果您删除 rwlock 代码 - 它不会改变行为。

  2. 我看不到 pthread_rwlock_init() 调用,假设您在另一个地方调用了它。无论如何请注意,您确实调用了它并且您不要调用它两次或使用同一个行锁对象多次。

    这同样适用于pthread_rwlockattr_destroy()

  3. 我看不出 pthread_rwlock_rdlock() 在没有写锁的情况下会阻塞的原因。确保你不这样做。或者你可以对你的 mutex

    进行互锁

关于linux - 条件变量和rwlock死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19887765/

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