std::thread calling method of class

C++MultithreadingC++11

C++ Problem Overview


> 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.

C++ Solutions


Solution 1 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkobraView Question on Stackoverflow
Solution 1 - C++Kerrek SBView Answer on Stackoverflow