2013-03-31 66 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()如我所料,這是意圖)

相關問題