线程函数未被调用.语法有什么问题吗

thread function is not called. Is there anything wrong with the syntax

本文关键字:什么 问题 语法 调用 函数 线程      更新时间:2023-10-16

不调用线程函数"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

pthread_create期望回调具有以下签名:

void *(*start_routine) (void *)

您传入一个返回值的回调。这不会破坏堆栈吗?例如,函数推送到堆栈,但调用方从不弹出它,因为它什么都不期望?