Skip to content

Instantly share code, notes, and snippets.

@eruffaldi
Created August 11, 2016 10:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eruffaldi/7180bdec4c8c9a11f019dd0ba9a2d68c to your computer and use it in GitHub Desktop.
Save eruffaldi/7180bdec4c8c9a11f019dd0ba9a2d68c to your computer and use it in GitHub Desktop.
OpenMP custom reduction example
// g++-mp-4.9 -fopenmp --std=c++11 x.cpp -lgomp
#include <iostream>
#include <omp.h>
#include <unistd.h>
class Custom
{
public:
Custom(int y = 0) : x(y) {}
Custom& operator += (const Custom & other)
{
x += other.x;
return *this;
}
int x = 0;
};
// not needed
Custom operator + (const Custom & a, const Custom & other)
{
return Custom(a.x+other.x);
}
//https://software.intel.com/en-us/node/583439
//page 180 of: http://www.openmp.org/mp-documents/OpenMP4.0.0.pdf
#pragma omp declare reduction(CustomPlus: Custom: \
omp_out += omp_in)
// initializer (omp_priv=Custom(100))
int main(int argc, char * argv[])
{
Custom sum(0);
Custom a[100];
for(int i = 0; i < 100; i++)
a[i].x = 100;
{
#pragma omp parallel for reduction(CustomPlus:sum)
for(int i = 0; i < 100; i ++)
{
#pragma omp critical
{
std::cout << " " << i << " " << omp_get_thread_num() << std::endl;
}
usleep(1000);
Custom val(i*2+a[i].x);
sum += val;
}
}
std::cout << sum.x << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment