Is pthread_join a must when using pthread in linux?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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

回答1:

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().



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!