在Linux中使用的pthread时,在pthread_join必须的? [英] Is pthread_join a must when using pthread in linux?

查看:438
本文介绍了在Linux中使用的pthread时,在pthread_join必须的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的学习的pthread 和我有几个问题。

下面是我的code:

 的#include< pthreads.h中>
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&iostream的GT;
#定义NUM_THREADS 10使用命名空间std;无效* PrintHello(void *的主题ID)
{
   INT * TID;
   TID =(INT *)主题ID;
   的for(int i = 0;我小于5;我++){
     的printf(你好,世界(线程%D)\\ n,* TID);
   }
   了pthread_exit(NULL);
}INT主(INT ARGC,CHAR *的argv [])
{
   的pthread_t线程[NUM_THREADS];
   INT RC;
   INT吨;
   为int * valPt [NUM_THREADS];   对于(t = 0; T< NUM_THREADS;吨++){
      的printf(在主:创建线程%d个\\ N,T);
      valPt [T] = INT新();
      * valPt [T] = T;
      RC =在pthread_create(安培;螺纹[T],NULL,PrintHello,(无效*)valPt [T]);
      如果(RC){
         的printf(ERROR;从pthread_create的收益code()为%d \\ n,RC);
         出口(-1);
      }
   }
   / *最后一件事是主要的()应该做的* /
   了pthread_exit(NULL);
}

在code运行良好,我不叫在pthread_join 。所以,我想知道,是在pthread_join 一绝?


另一个问题是:

  valPt [T] = INT新();
* valPt [T] = T;
RC =在pthread_create(安培;螺纹[T],NULL,PrintHello,(无效*)valPt [T]);

等于:

  RC =在pthread_create(安培;螺纹[T],NULL,PrintHello,和放大器;我);


解决方案

这是不。但是,您需要使用了pthread_exit()在pthread_join()
在这里,你就叫了pthread_exit(),这就是为什么子线程继续执行主线程终止后还是一样。
如果有任何需要主线程要等到子线程完成执行,你可以使用在pthread_join()

I an learning pthread and I have a few questions.

Here is my code:

#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);
}

The code runs well and I don't call pthread_join. So I want to know, is pthread_join a must?


Another issue, is:

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

equal to:

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

解决方案

It is not. But you need either pthread_exit() or pthread_join(). Here you called pthread_exit(), thats why the child threads continue execution even after the main thread terminates. If there is any need for the main thread to wait till the child threads complete execution, you can use pthread_join().

这篇关于在Linux中使用的pthread时,在pthread_join必须的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆