C++0x 线程初始化

c++0x thread initlization

本文关键字:初始化 线程 C++0x      更新时间:2023-10-16

可能的重复项:
使用成员函数启动线程

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

例如,如果我有

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

然后在 A 类的构造函数中,我想用 doSomething 启动一个线程。如果我像下面这样写,我会收到错误,指出 doSomething 未解决。我甚至>做某事。

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

试试这个:

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

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;
}