2013-04-04 50 views
0

我試圖執行一個線程對象像這樣調用時:在pthread_create什麼都不做,從一個包裝函數

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

class Thread 
{ 
private: 
    int id; 
    static void * run(void * arg) 
    { 
     int tid = (int)arg; 
     std::cout << "Thread " << tid << " executed." <<std::endl; 
     pthread_exit(NULL); 
    } 
public: 
    Thread(int _id); 
    void start(); 
    int get_id(); 
}; 

這裏的公共方法&構造函數的實現:

#include "std_thread.h" 

Thread::Thread(int _id) 
{ 
    id = _id; 
} 

void Thread::start() 
{ 
    std::cout << "Thread created." <<std::endl; 
    pthread_t thread; 
    int rc = pthread_create(&thread, NULL, run, (void*)id); 
    if(rc) 
     std::cout << "Return code from thread is " << rc; 
} 

int Thread::get_id() 
{ 
    return id; 
} 

而這裏的主要:

#include "std_thread.h" 

int main() 
{ 
    Thread *thd = new Thread(0); 
    thd->start(); 

    return 0; 
} 

當我創建線程對象並調用它的啓動方法,這反過來應該打印「線程創建」。並運行線程體 - 它不;實際上,它確實打印了創建到控制檯的線程,但似乎沒有創建線程,或者線程沒有做任何事情。順便一提所有東西都編譯好了,沒有運行時錯誤。

任何想法?

+1

在哪裏,這裏在pthread_join? – ForEveR 2013-04-04 11:57:39

+0

加入一個連接解決了它。任何理由? – stellarossa 2013-04-04 12:13:40

回答

1

您的main在線程有機會運行之前返回。

程序不會等到所有線程完成退出之前完成 - 一旦main結束,程序結束,程序關閉。

pthread_t thread;作爲成員而不是局部變量,並添加一個方法來等待線程完成。
這是我能想出的最簡單的例子:

void Thread::wait() 
{ 
    pthread_join(thread, NULL); 
} 

int main() 
{ 
    Thread thd(0); // There's no point in using dynamic allocation here. 
    thd.start(); 
    thd.wait(); 
    return 0; 
}