std :: thread调用类的方法

时间:2012-06-12 14:29:27

标签: c++ multithreading c++11

  

可能重复:
  Start thread with member function

我有一个小班:

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

如何在方法calculate的两个线程中使用两组不同的参数(例如calculate(0,10)calculate(11,20))运行方法runMultiThread()

PS谢谢我忘记了我需要传递this作为参数。

1 个答案:

答案 0 :(得分:151)

不那么难:

#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();
}
相关问题