std::类的线程调用方法

std::thread calling method of class

本文关键字:调用 方法 线程 std      更新时间:2023-10-16

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

我有一个小班:

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

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

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

没那么难:

#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();
}