Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenMP min reduction and std::min

Tags:

c++

min

openmp

I am testing OpenMP min reduction. If I write my code like the following, it will return the correct result: res = 3.

#include <omp.h>
#include <iostream>
#include <algorithm>

int main(){

    omp_set_num_threads(5);

    float res=10;

#pragma omp parallel for default(shared) reduction(min:res)
    for(int i1 = 0; i1 <= 10; i1++)
        for(int i0 = 0; i0 <= 10; i0++)
            if(res > 3.0+i1+20*i0)
                res = 3.0+i1+20*i0;

    std::cout << "res = " << res << std::endl;

    return 0;
}

But If I write in an alternative way by replacing "if" statement with "std::min", then the result is wrong: res = 10.

#include <omp.h>
#include <iostream>
#include <algorithm>

int main(){

    omp_set_num_threads(5);

    float res=10;

#pragma omp parallel for default(shared) reduction(min:res)
    for(int i1 = 0; i1 <= 10; i1++)
        for(int i0 = 0; i0 <= 10; i0++)
            res = std::min(res,static_cast<float>(3.0+i1+20*i0));

    std::cout << "res = " << res << std::endl;

    return 0;
}

Is OpenMP min reduction interfering with std::min?

like image 805
llodds Avatar asked Sep 08 '16 14:09

llodds


1 Answers

First of all, your code is conforming: it shouldn't matter which kind of code you have inside the parallel for.

What the reduction clause implies is that each thread will have its own private copy initialized to the neutral element of the min operator (i.e. the largest representable number in the reduction item type) and they will work with it until the end of the construct. At that point, these private copies will be reduced to the original list item using the reduction-identifier, which in your case is the min operator. So there is no race-condition here.

I have executed your code using the same version as you did and it worked fine: icpc (ICC) 16.0.0 and OpenMP version 201307. Could this issue be related to the C++ standard headers that you are using?

like image 193
smateo Avatar answered Oct 09 '22 18:10

smateo