【问题标题】:Pthread join or pthread exit of terminating mulithreaded c program?终止多线程c程序的pthread加入或pthread退出?
【发布时间】:2021-04-06 15:58:45
【问题描述】:

我想为 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;
}

【问题讨论】:

  • 能否请您统一格式化您的代码?此外,这可能是用 C 或 C++ 编译的,所以添加相应的语言标签。此外,这应该是一个minimal reproducible example,所以如果可能的话,将它从三个减少到更少的额外线程。作为这里的新用户,也请带上tour并阅读How to Ask
  • 谢谢!!!我会记住这一点的!
  • 你仍然可以edit你的问题!

标签: multithreading pthreads


【解决方案1】:

我应该如何终止线程?

无论是从最外层调用返回线程函数还是调用pthread_exit() 都会终止线程。从最外层调用返回值p 等效于调用pthread_exit(p)

程序卡住了

当程序执行时当然会这样做

   while(1);

.

另外,我尝试删除 main 中的 while (1) 并在那里使用 pthread join。但是,我得到了相同的结果。

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

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

【讨论】:

  • 非常感谢!!!!!!!!!!!!!!!!!!快乐学习!!!!!!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多