Nick Banks
Nick Banks

Reputation: 4408

Threaded for loop in c++

I am trying to figure out the best way to essentially thread a for loop. For example, if I have the following loop:

for(int i = 0; i < n; i++)
  doSomethingThreadSafe(i);

This will be on a Windows platform. I have played around with creating a thread for each processor, and then attempting to divide n up as evenly as possible for each processor. Then I pass the necessary data to each thread, and then use a WaitForMultipleThreads. Is there a better way to do this? I don't want to use any other library like boost.

Ideally, I would like some generic (perhaps templated) way to go about this. i.e.

threaded_for(0, n, doSomethingThreadSafe);

If the best/most efficient way would to be use a library, how much work would be required to add the library, and how exactly would it be used in this example. Still, I prefer a solution with out requiring something else to be added.

Upvotes: 3

Views: 1052

Answers (2)

Martin Beckett
Martin Beckett

Reputation: 96109

Easiest way is openMP - visual studio supports it as standard, you just add a couple of magic #pragma to the loop and use all the cores you have !

Best way to learn is how not to do it - 32 OpenMP Traps For C++ Developers

An alternative - but slightly more complex method Intel TBB

Upvotes: 5

user257111
user257111

Reputation:

By far the most efficient way to solve this problem, assuming doSomethingThreadSafe(i) is basically a repeated instruction (single instruction on multiple data) is to use OpenMP as chrisaycock says.

#pragma omp parallel for
for ( i = 0; i < n; i++ )
    doSomethingThreadSafe(i);

It can't get much more simple than that, really.

Upvotes: 2

Related Questions