main idea
This can be done without any palellelization-break critical or atomic sections, creating a custom shorthand . Basically, define an object that stores both the index and value, and then create a function that sorts two of these objects only by value, and not by index.
More details
An object to store the index and value together:
typedef std::pair<unsigned int, float> IndexValuePair;
You can access the index by accessing the first property and the value by accessing the second property, i.e.
IndexValuePair obj(0, 2.345); unsigned int ix = obj.first;
Define a function to sort two IndexValuePair objects:
IndexValuePair myMin(IndexValuePair a, IndexValuePair b){ return a.second < b.second ? a : b; }
Then create a custom reduction as recommended in the OpenMP documentation:
#pragma omp declare reduction \ (minPair:IndexValuePair:omp_out=myMin(omp_out, omp_in)) \ initializer(omp_priv = IndexValuePair(0, 1000))
In this case, I decided to initialize the index to 0 and the value 1000. The value should be initialized to a number greater than the largest value that you expect to sort.
Functional example
Finally, combine all of these parts with a parallel loop!
// Compile with g++ -std=c++11 -fopenmp demo.cpp
source share