2013-03-31 67 views
15

我正在尝试使用C++ 11的std::thread类来运行并行执行的类的成员函数。如何在使用C++ 11线程类的单独线程中执行类成员函数?

头文件的代码类似于:

class SomeClass { 
    vector<int> classVector; 
    void threadFunction(bool arg1, bool arg2); 
public: 
    void otherFunction(); 
}; 

cpp文件是类似于:在Mac OS X 10.8.3

void SomeClass::threadFunction(bool arg1, bool arg2) { 
    //thread task 
} 

void SomeClass::otherFunction() { 
    thread t1(&SomeClass::threadFunction, arg1, arg2, *this); 
    t1.join(); 
} 

我使用的Xcode 4.6.1。我使用的编译器是Xcode附带的Apple LLVM 4.2。

上述代码无效。编译器错误说"Attempted to use deleted function"

在线程创建线上,它显示以下按摩。

In instantiation of function template specialization 'std::__1::thread::thread<void (SomeClass::*)(bool, bool), bool &, bool &, FETD2DSolver &, void>' requested here 

我是新的C++ 11和线程类。有人能帮助我吗?

回答

21

的情况下应该是第二个参数,就像这样:

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2); 
+7

这是值得指出的是,有机磷农药的代码是无用的,如果他称之为'。加入()'立刻。 –

+0

非常感谢它的工作。 –

1

我仍然有与上述答案(?我想应该是抱怨它无法在智能指针复制)问题,所以改写它用拉姆达:

void SomeClass::otherFunction() { 
    thread t1([this,arg1,arg2](){ threadFunction(arg1,arg2); }); 
    t1.detach(); 
} 

然后它编译并运行良好。 AFAIK,这是一样高效,并且我个人觉得它更可读。

(注:我也改变join()detach()如我所料,这是意图)

相关问题