【问题标题】:thread function is not called. Is there anything wrong with the syntax未调用线程函数。语法有什么问题吗
【发布时间】:2014-10-11 09:45:55
【问题描述】:

未调用线程函数“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 是否有任何错误。

提前致谢。

【问题讨论】:

    标签: c++ multithreading pthreads


    【解决方案1】:

    您的程序可能在您的线程开始之前就退出了。您需要在退出 main 之前加入您的线程。

    用途:

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

    【讨论】:

      【解决方案2】:

      pthread_create 需要具有以下签名的回调:

      void *(*start_routine) (void *)
      

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

      【讨论】:

      • 该签名具有 (void *) 返回类型,所以没有问题。
      • 我对这个答案投了赞成票,因为我在 CreateThread 中遇到了类似的问题,它的启动函数返回了一个值并且从未被调用过。我删除了返回值,它起作用了。
      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2013-04-04
      • 2016-10-05
      相关资源
      最近更新 更多