std ::线程调用类的方法 [英] std::thread calling method of class

查看:165
本文介绍了std ::线程调用类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

具有成员函数的开始线程


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

如何运行方法计算有两个不同的参数集(例如 calculate(0,10) calculate(11,20) c)在方法 runMultiThread()



的两个线程中感谢我忘记了我需要pass <

解决方案

不要那么难:

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


Possible Duplicate:
Start thread with member function

I have a small class:

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

How its possible to run method calculate with two differents set of parametrs(for example calculate(0,10), calculate(11,20)) in two threads from method runMultiThread()?

PS Thanks I have forgotten that I need pass this, as parameter.

解决方案

Not so hard:

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

If the result of the computation is still needed, use a future instead:

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

这篇关于std ::线程调用类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆