3

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.

6
  • 3
    Since you don't want to use an outside library, you won't be able to use OpenMP, which is really what you should be using in this case. Commented Jan 29, 2011 at 4:42
  • what are you actually doing in your threads? will there be shared resources that require synchronization? Commented Jan 29, 2011 at 4:48
  • @ThomasMcLeod Everything has been setup so that no synchronization will be required. They will all be doing things independently. Commented Jan 29, 2011 at 4:50
  • In that case, what's the issue? Are you trying to divide the work evenly? Commented Jan 29, 2011 at 4:54
  • 2
    Can parallel_for help you? msdn.microsoft.com/en-us/library/dd505035.aspx Commented Jan 29, 2011 at 4:56

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.