c++0x 线程初始化

标签 c++ multithreading c++11

<分区>

Possible Duplicate:
Start thread with member function

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

例如,如果我有

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

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

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

关于c++0x 线程初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14596809/

相关文章:

c++ - 这个基数有多少位?

c++ - C 代码中的 C4201 警告

c++ - 自动检测模板函数的返回类型

Java 同步实例成员不能以嵌套方式工作

c++ - 存在 lambda 参数时 ADL 失败?

c++ - 初始化模板参数长度的非默认可构造对象数组

c++ - OpenGl 显示动画和绘制文本

c++ - 来自 glGetError() 的 INVALID_ENUM 错误。 glGetError 与 glu、glew、glfw?

c - C 中的多线程错误段错误

c++ - std::move 操作 C++