2013-04-18 84 views
0

我使用pthread.h運行下面的代碼... 運行一段時間,該線程完成之前,該代碼退出...過程中,所有線程都結束了沒有完成

我附代碼...

#include<iostream> 
#include<pthread.h> 

using namespace std; 

#define NUM_THREADS 5 

void *PrintHello(void *threadid) 
{ 
    long tid = (long)threadid; 
    cout<<"Hello World! Thread ID,"<<tid<<endl; 
    pthread_exit(NULL); 
    return &tid; 
} 

int main() 
{ 
    pthread_t threads[NUM_THREADS]; 
    int rc; 
    int i; 

    for(i=0;i<NUM_THREADS;i++) 
    { 
     cout<<"main() : creating thread,"<<i<<endl; 
     rc = pthread_create(&threads[i],NULL,PrintHello,(void*)i); 
     //sleep(1); 
     if(rc) 
     { 
      cout<<"Error:Unable to create thread,"<<rc<<endl; 
      exit(-1); 
     } 
    } 

    pthread_exit(NULL); 

    return 0; 
} 

回答

3

您應該join主調用pthread_exit之前的所有線程。

for (i = 0; i < NUM_THREADS; i++) 
{ 
    pthread_join(threads[i], 0); 
} 
+0

是的,謝謝..它的工作..請說什麼是睡眠()函數和它是哪個頭? –

+0

@Vinoj [Sleep](http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html) –

1

在你的主,你做什麼,

pthread_exit(NULL); // this causes main to do its own work and exit. 
         // and the other thread will keep running at its own pace 

如前所述here

,你必須使用類似

for (i = 0; i < NUM_THREADS; i++) 
{ 
    pthread_join(&threads[i],NULL); 
} 

使它等待所有線程結束在繼續之前