gpt4 book ai didi

c - 多线程中的死锁

转载 作者:行者123 更新时间:2023-11-30 16:37:05 25 4
gpt4 key购买 nike

这段代码出现死锁。有时有效,有时无效。我有以下带有 3 个线程和互斥体的简单代码。我希望每个线程都等待,然后在所有线程都等待之后,向第一个线程发出信号,然后向第二个线程发出信号,然后向第二个、第三个发出信号。

void *thread1(void *a) {
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "Thread %d.\n", 1);
pthread_cond_signal(&cond);//release wait
pthread_exit(NULL);
}
void *thread2(void *a) {
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "Thread %d.\n", 2);
pthread_cond_signal(&cond);//release wait
pthread_exit(NULL);
}
void *thread3(void *a){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "Thread %d.\n", 3);
pthread_cond_signal(&cond);//release wait
pthread_exit(NULL);
}

for(int i=0;i<3;i++)
pthread_create(&threads[i], &attr, (void *) timer, (void *) timer);

pthread_cond_signal(&cond);//release wait
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);

最佳答案

问题在于主线程的pthread_cond_wait可能会在所有pthread_cond_signal执行完之后才被执行。如果主线程必须等待所有线程的终止,您可以使用pthread_join,甚至信号量,但我认为这有点矫枉过正。

另一个问题是第一个释放的线程(比如说thread1)可以释放主线程(而不是thread2和/或thread3),所以你只看到一个线程的输出,然后你的程序终止。再次发生这种情况只是因为主线程不等待 thread1thread2thread3

关于c - 多线程中的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48130245/

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