Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openmp Reduction for operator "-"

Tags:

c++

openmp

int main()
{
    int a=0;
    omp_set_num_threads(2);
    #pragma omp parallel reduction(+ : a)
    {
        a = omp_get_thread_num()+1;
    }
    std::cout << "Output:" << a;
    return 1;
}

I am getting wrong output using openmp reduction... For the following code, reduction(+) gives the output of sum of threadnum(), but when i mention reduction (-), it gives the same output... I am getting output as 3 for "+" and "-".

like image 927
noorul Avatar asked Oct 21 '25 11:10

noorul


1 Answers

Reduction in OpenMP functions as follows: each thread is given its local copy of the reduction variable and operations such as += and -= affect the local copy. Then at the end the following reduction operation is performed:

a = init_value op a_0 op a_1 op a_2 op ... op a_(N-1)

where N is the number of threads and init_value is the initialisation value for the reduction operation. The initialisation value for both + and - reduction operations is 0 (zero). There is a catch with the subtraction though and it is explained in the OpenMP standard as a comment to the way that the final value is formed (§2.9.3.6 reduction clause):

(The partial results of a subtraction reduction are added to form the final value.)

This means that with reduction(-:a) you still get all private values added together, i.e. both + and - reductions are equivalent. This is the correct way to implement it since it is assumed that the - reduction will only be coupled with the var -= expr or var = var - expr expressions. Therefore your program is not conforming to the standard and you get what you deserve for not reading into the intricate details of OpenMP.

The correct example with reduction(-:a) would be:

#pragma omp parallel reduction(-:a)
{
    a -= omp_get_thread_num() + 1;
}
like image 55
Hristo Iliev Avatar answered Oct 22 '25 23:10

Hristo Iliev