2014-10-11 63 views
0

不調用線程函數「get_singleton」函數。我甚至沒有在屏幕上看到任何錯誤。線程函數未被調用。語法有什麼問題

class singleton{ 
private: singleton(){cout<<"constructor called";} 
    singleton(singleton&); 
    singleton& operator =(singleton &); 
    ~singleton(); 

public: static singleton *s; 
static singleton* get_singleton(); 
static pthread_mutex_t t; 

}; 
pthread_mutex_t singleton::t=PTHREAD_MUTEX_INITIALIZER; 
singleton* singleton::s=NULL; 
singleton* singleton::get_singleton() 
{ 
cout<<"get_singleton called"; 
if(s==NULL) 
{ 
    usleep(300);  
    s=new singleton(); 
} 

return s; 
} 

int main(int argc, char *argv[]) 
{ 
int err; 
pthread_t t1,t2; 
err=pthread_create(&t1,NULL,(void *(*)(void *))singleton::get_singleton,NULL); 
if(err!=0) 
    cout<<"unable to create thread"; 
err=pthread_create(&t2,NULL,(void *(*)(void *))singleton::get_singleton,NULL); 
if(err!=0) 
    cout<<"unable to create thread"; 

cout<<"end of func"<<endl; 
return 0; 
} 

在調用「get_singleton」函數時,「pthread_create」api中是否有任何錯誤。

在此先感謝。

回答

3

在你的線程開始之前,你的程序可能會退出。你需要在退出main之前加入你的線程。

用途:

pthread_join(t1, NULL); // or nullptr if C++ >= 11, but then you could 
pthread_join(t2, NULL); // use std::thread instead 
0

在pthread_create預計具有以下簽名的回調:

void *(*start_routine) (void *) 

你傳遞一個返回值的回調。這不會破壞堆棧嗎?例如。該函數會推入堆棧,但調用者永遠不會彈出它,因爲它什麼都不需要?

+0

該簽名具有('void *')返回類型,所以沒有問題。 – Mat 2014-10-11 09:57:22

+0

是的,你是對的,我的錯 – 2014-10-11 09:58:09