web-dev-qa-db-ja.com

C ++ 11スレッドクラスを使用して別のスレッドでクラスメンバー関数を実行するにはどうすればよいですか?

C++ 11のstd::threadクラスを使用して、クラスのメンバー関数を実行して並列実行しようとしています。

ヘッダーファイルのコードは次のようになります。

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

Cppファイルは次のようなものです。

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

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

Mac OS X10.8.3でXcode4.6.1を使用しています。私が使用しているコンパイラは、Xcodeに付属のApple LLVM4.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とスレッドクラスの初心者です。誰かが私を助けることができますか?

16
Raiyan Kabir

次のように、インスタンスは2番目の引数である必要があります。

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
22
Kerrek SB

私はまだ上記の答えに問題がありました(スマートポインターをコピーできないと不平を言っていたと思いますか?)ので、ラムダで言い換えました:

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

その後、コンパイルして正常に実行されました。 AFAIK、これは同じくらい効率的で、個人的にはもっと読みやすいと思います。

(注:意図したとおり、join()detach()に変更しました。)

1
Darren Cook