2016-06-29 14 views
0

我是學習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); 
+0

第二個問題的答案:呃,這兩個看起來完全和完全不同於我。我的建議是使用'reinterpret_cast (i)',因爲這是C++而不是C,因爲問題被標記。 –

+0

下面是關於傳遞值到'pthread_create'的討論:http://stackoverflow.com/questions/8487380/how-to-cast-an-integer-to-void-pointer/8487738#8487738 –

+0

線程被「釋放」無論是當你加入它,或當它完成時,如果它是分離的。如果它沒有被分離,並且你不加入它,你就會漏掉它。 – immibis

回答

1

它不是。但您需要pthread_exit()pthread_join()。 這裏你稱爲pthread_exit(),這就是爲什麼子線程即使在主線程終止後仍然繼續執行。 如果主線程需要等待子線程完成執行,您可以使用pthread_join()

+0

因此,在其中一個並行線程中調用exit()將終止main,並且兄弟姐妹會死亡?但是pthread_exit()允許它們運行,如果他們知道父進程已經離開,它可能會優雅地和早地終止?更重要的是父母可能不是主要的? – mckenzm

相關問題