2012-03-10 96 views
0

我是新來的,並用pthread編程noob。 我的問題是在一個C++類,我試圖創建封裝線程。 閱讀我看到,當我創建一個pthread時,我需要將C函數傳遞給它在啓動時運行的pthread_create ...因此,當pthread運行該函數時,它不會在標準輸出上輸出消息!沒有cout打印pthread啓動功能

但它的更好,如果你看到的代碼: (顯然這是副本,並從網上教程貼^^)

void *runAtStart(void *threadid) 
{ 

    long tid; 
    tid = (long)threadid; 

    printf("Hello World! It's me, thread #%ld!\n", tid); 
    pthread_exit(NULL); 
} 


Thread::Thread() { 
    pthread_t threads[1]; 
    int rc; 
    long t; 
    for(t=0; t<1; t++){ 
     printf("In main: creating thread %ld\n", t); 
     rc = pthread_create(&threads[t], NULL, runAtStart, (void *)t); 
     if (rc){ 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     // exit(-1); 
     } 
    } 
} 

我稱這個爲:

int main() 
{ 
    Thread *th=new Thread(); 
    return 0; 
} 

的產生的輸出是:

In main: creating thread 0 

我希望有人明白了! 對不起我的英文! :) Inzirio

回答

0

您的程序運行良好。你看到的問題是你的main()函數在你的線程能夠真正運行之前返回,這會導致你的程序退出。

證明這一點的一個簡單方法是在您的回電之前在main()中添加sleep(5);。一個更好的方法是找到一種方式來讓main()等到它的所有線程都返回之前完成。一種合理的方式是爲你的Thread類添加一個析構函數來執行pthread_join,並確保你真的調用了析構函數:delete th;

+0

謝謝我會試試!我不會那麼想! ;) – inzirio 2012-03-10 16:21:17