【问题标题】:Is pthread_join a must when using pthread in linux?在 linux 中使用 pthread 时必须使用 pthread_join 吗?
【发布时间】:2016-10-31 14:38:33
【问题描述】:

我正在学习pthread,我有几个问题。

这是我的代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM_THREADS 10

using namespace std;

void *PrintHello(void *threadid)
{
   int* tid;
   tid = (int*)threadid;
   for(int i = 0; i < 5; i++){
     printf("Hello, World (thread %d)\n", *tid);
   }
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   int t;
   int* valPt[NUM_THREADS]; 

   for(t=0; t < NUM_THREADS; t++){
      printf("In main: creating thread %d\n", t);
      valPt[t] = new int();
      *valPt[t] = t;
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   /* Last thing that main() should do */
   pthread_exit(NULL);
}

代码运行良好,我不调用pthread_join。所以我想知道,pthread_join 是必须的吗?


另一个问题是:

valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);

等于:

rc = pthread_create(&threads[t], NULL, PrintHello, &i);

【问题讨论】:

  • 第二个问题的答案:呃,这两个在我看来完全不同。我的建议是使用reinterpret_cast&lt;void *&gt;(i),因为这是 C++ 而不是 C,因为问题已被标记。
  • 这里讨论了将值传递给pthread_createstackoverflow.com/questions/8487380/…
  • 一个线程在你加入它时被“释放”,或者当它完成时它被分离。如果它没有分离并且你不加入它,你就是在泄漏它。
  • 1. pthread_join 是必须的,因为主线程(创建其他线程的线程)可能会在创建的线程完成之前完成执行,并且您通常会为冗长的任务创建线程。这也是一种同步线程的方法。 2. 你真的不需要 valPt(而且你现在也在泄漏 valPt[t])。

标签: c linux pthreads


【解决方案1】:

事实并非如此。但是您需要pthread_exit()pthread_join()。 在这里,您调用了pthread_exit(),这就是为什么即使在主线程终止后子线程仍继续执行的原因。 如果主线程需要等待子线程执行完毕,可以使用pthread_join()

【讨论】:

  • 所以在其中一个并行线程中调用 exit() 将终止 main 并且兄弟姐妹死于“肮脏”的死亡?但是 pthread_exit() 允许他们继续运行,如果他们知道父母已经走了,可能会优雅地提前终止?更重要的是,父母可能不是主要的?
猜你喜欢
  • 2018-10-28
  • 2019-08-12
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多