终止多线程 c 程序的 Pthread 加入或 pthread 退出?

Pthread join or pthread exit of terminating mulithreaded c program?

我想为 3 个线程打印 1 到 10。我的代码能够做到这一点,但之后程序就卡住了。我尝试在函数末尾使用 pthread_exit 。另外,我尝试删除 main 中的 while (1) 并在那里使用 pthread join 。但是,我仍然得到了相同的结果。我应该如何终止线程?

enter code here
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>



int done = 1;



//Thread function

void *foo()
{
    for (int i = 0; i < 10; i++)
    {
         printf("  \n @@@@@@@@@@@@@");
        pthread_mutex_lock(&lock);

        if(done == 1)
        {
            done = 2;
            printf (" \n %d", i);
            pthread_cond_signal(&cond2);
            pthread_cond_wait(&cond1, &lock);
            printf (" \n Thread 1 woke up");
        }
        else if(done == 2)
        {
            printf (" \n %d", i);
            done = 3;
             pthread_cond_signal(&cond3);
            pthread_cond_wait(&cond2, &lock);
            printf (" \n Thread 2 woke up");
        }
        else
        {
            printf (" \n %d", i);
            done = 1;
             pthread_cond_signal(&cond1);
            pthread_cond_wait(&cond3, &lock);
            printf (" \n Thread 3 woke up");
        }
      
      
      pthread_mutex_unlock(&lock);


        }
 

    pthread_exit(NULL);
    return NULL;
}


int main(void)
{
  
    pthread_t tid1, tid2, tid3;

    pthread_create(&tid1, NULL, foo, NULL);
     pthread_create(&tid2, NULL, foo, NULL);
      pthread_create(&tid3, NULL, foo, NULL);

   
   while(1);
 printf ("\n $$$$$$$$$$$$$$$$$$$$$$$$$$$");
    return 0;
}

How should I terminate the threads?

要么从最外层调用线程函数返回,要么调用pthread_exit()终止一个线程。从最外层调用返回值 p 等同于调用 pthread_exit(p).

the program gets stuck

当然是在程序执行的时候

   while(1);

.

Also, I tried to remove while (1) in main and using pthread join there. But still, I got the same result.

需要加入线程以确保它们在整个程序结束之前终止。这是实现这一目标的唯一合适方法。但是,如果您的线程实际上没有首先终止,那就没有意义了。

在你的例子中,观察每个线程在循环的每次迭代中无条件地执行 pthread_cond_wait(),要求它在恢复之前发出信号。通常,前一个线程会向它发出信号,但在循环的最后一次迭代之后不会发生这种情况。您可以通过让每个线程在退出循环后对 pthread_cond_signal() 执行适当的额外调用,或者确保线程在最后一次循环迭代中不等待来解决这个问题。