91

重複の可能性:
メンバー関数でスレッドを開始します

私は少人数のクラスを持っています:

class Test
{
public:
  void runMultiThread();
private:
  int calculate(int from, int to);
}  

メソッドの2つのスレッドでcalculate2つの異なるパラメーターのセット(たとえばcalculate(0,10)、 )を使用してメソッドを実行するにはどうすればよいですか?calculate(11,20)runMultiThread()

thisPSありがとうございます。パラメータとしてパスが必要であることを忘れてしまいました。

4

1 に答える 1

225

それほど難しくはありません:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

計算の結果がまだ必要な場合は、代わりにfutureを使用してください。

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}
于 2012-06-12T14:32:03.820 に答える