109

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()?

0

1 Answer 1

259

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(); } 
Sign up to request clarification or add additional context in comments.

14 Comments

@ravenspoint: Whether it's threadsafe is up to the OP, non? I agree that the return value should be recovered, though the OP doesn't indicate that that's intended (it could be like printf). std::async would be an alternative.
@JonathanWakely Maybe because the OP asked so? Though we don't know if his approach is correct in the first place, but maybe he does other computations meanwhile.
@ravenspoint: The question asked how to run a function in different threads with different arguments, and this answer clearly demonstrates how to do that. How is that not useful?
@ravenspoint: Those are other questions; and there can more other questions as well.
I didn't think that the number of threads would be a point of contention. I'm merely demonstrating the techniques; I'm confident the OP can arrange the code in any fashion that suits her ultimate concurrency needs.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.