Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread calling method of class [duplicate]

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.

like image 750
kobra Avatar asked Jun 12 '12 14:06

kobra


1 Answers

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();
}
like image 100
Kerrek SB Avatar answered Oct 25 '22 11:10

Kerrek SB