我是學習pthread
,我有幾個問題。在linux中使用pthread時,pthread_join是必須的嗎?
這裏是我的代碼:
#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(i)',因爲這是C++而不是C,因爲問題被標記。 –
下面是關於傳遞值到'pthread_create'的討論:http://stackoverflow.com/questions/8487380/how-to-cast-an-integer-to-void-pointer/8487738#8487738 –
線程被「釋放」無論是當你加入它,或當它完成時,如果它是分離的。如果它沒有被分離,並且你不加入它,你就會漏掉它。 – immibis