开发者

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜