std::thread 调用类的方法[重复]

问题描述 投票:0回答:1

可能重复:
使用成员函数启动线程

我有一个小班:

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

如何在方法

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

c++ multithreading c++11
1个回答
256
投票

没那么难:

#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();
}
© www.soinside.com 2019 - 2024. All rights reserved.