2014-10-11 65 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