线程函数“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 是否有任何错误。
提前致谢。
最佳答案
您的程序可能在您的线程启动之前就退出了。您需要在退出 main 之前加入您的线程。
使用:
pthread_join(t1, NULL); // or nullptr if C++ >= 11, but then you could
pthread_join(t2, NULL); // use std::thread instead
关于c++ - 不调用线程函数。语法有什么问题吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313289/