C语言 多线程中的死锁



我在这个代码中死锁了。它有时有效,有时无效。我有以下带有 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_signal之后,可能会执行主线程的pthread_cond_wait。如果主线程必须等待所有线程的终止,您可以使用pthread_join,甚至信号量,但我认为这有点矫枉过正。

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

最新更新