c ++ 0x线程初始化

时间:2013-01-30 04:40:14

标签: c++ multithreading c++11

  

可能重复:
  Start thread with member function

在c ++ 0x中用class方法定义一个线程构造函数,如下所示,我得到的函数无法解析。我做错了什么?

例如,如果我有

#include <thread>
 using namespace std;
class A
{
 public:
    void doSomething();
    A();
}

然后在A类的构造函数中,我想用doSomething启动一个线程。如果我写得如下,我得到的错误是没有解决的事情。我甚至这个 - >做某事。

 A::A()
 {
     thread t(doSomething);
  }

1 个答案:

答案 0 :(得分:4)

试试这个:

class A
{
 public:
   void doSomething();

   A()
   {
      thread t(&A::doSomething, this);
    }
};

OR

class A
{
 public:
   static void doSomething();

   A()
   {
      thread t(&A::doSomething);
    }
};

注意:您需要在某处加入您的主题,例如:

class A
{
public:
   void doSomething()
   {
      std::cout << "output from doSomething" << std::endl;
   }

   A(): t(&A::doSomething, this)
   {
   }
   ~A()
   {
     if(t.joinable())
     {
        t.join();
     }
   }

private:
  std::thread t;  
};

int main() 
{
    A a;        
    return 0;
}
相关问题