Suppose there is a vector odds, which stores the number of even and odd numbers, and there is a vector numbers, which stores these numbers themselves.

OpenMP parallelizable loop:

#pragma omp parallel for for (int i = 0; i < numbers.size(); ++i) { ++(odds[numbers[i] % 2]); } 

The serial and parallel versions of this cycle give different results. Where is the bug?

  • Some horror with formatting .. My first question)) - shl

2 answers 2

With atomic access, of course, you can, but the point? It will terribly slow down and the paralleling effect will simply not be noticeable.

I would write like this

 int uneven = 0, even = 0; #pragma omp parallel for reduction (+:uneven) reduction (+:even) for (i = 0; i < numbers.size(); i++) { (a[i]%2) ? (uneven++) : (even++); } odd[0] = even; odd[1] = uneven; 

The code may be somewhat clumsy, but it seems to me that it will work much more efficiently.

    Friends seem to understand! It is necessary to put #pragma omp atomic before the operation in the loop for correct access to the shared resource =)