尝试在c ++中创建简单线程时出错

时间:2014-06-27 16:15:56

标签: c++ multithreading

我试图创建一个简单的线程并让它执行。

我的功能定义是:

void MyClass::myFunction()
{
   //Do Work
}

我正在创建线程并执行它:

std::thread t1(myFunction);

编译我的代码后,我收到以下错误:

error C3867: function call missing argument list; use '&MyClass::myfunction' to create a pointer to member.

由于我的函数没有采用任何参数,我假设我在创建我的线程时错误地声明它?任何帮助将不胜感激,谢谢!!

1 个答案:

答案 0 :(得分:4)

  • 如果您的方法是非静态成员:您需要对象的实例来调用成员函数。
  • 如果您的方法是 static 成员,请执行编译器建议的操作:只需传递函数的地址。

示例

class A
{
    public:
        void foo() { cout << "foo"; }

        static void bar() { cout << "bar"; } 
};

int main() {
    std::thread t1(&A::foo, A()); // non static member
    t1.join();

    std::thread t2(&A::bar);   // static member (the synthax suggested by the compiler)
    t2.join();
    return 0;
}