Threaded for loop in C ++

I'm trying to find a better way to essentially stream the for loop. For example, if I have the following loop:

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

It will be on a Windows platform. I played with creating a thread for each processor, and then trying to split n as evenly as possible for each processor. Then I pass the necessary data to each thread, and then use WaitForMultipleThreads. Is there a better way to do this? I do not want to use any other library, for example boost.

Ideally, I would like some kind of general (possibly boilerplate) way around this. i.e.

threaded_for(0, n, doSomethingThreadSafe);

If the best / most efficient way is to use the library, how much work will be required to add the library and how exactly it will be used in this example. However, I prefer the solution without having to add another.

+3
source share
2 answers

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

The best way to find out how not to do this is 32 OpenMP Traps for C ++ Developers

An alternative but slightly more complicated Intel TBB method

+5
source

, , doSomethingThreadSafe (i) ( ), OpenMP, chrisaycock.

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

.

+2

Source: https://habr.com/ru/post/1788641/


All Articles