## Doing a reduction with MAX/MIN in C

General OpenMP discussion

### Doing a reduction with MAX/MIN in C

From the OpenMP documents (one example below):

https://computing.llnl.gov/tutorials/openMP/#REDUCTION

I see that intrinsics are supported in Fortran on "Reduce" clauses, but not in C! There is a very limited set of operators permitted for reduction clauses in C. Of course C does not have an intrinsic do max/min, but still this is a fairly common operation. So how does one do a "reduction" operation to find MIN or MAX in C in a parallel region?

Is using critical sections the only way to do this?

Thanks!
rreddy

### Re: Doing a reduction with MAX/MIN in C

There has been talk for quite a while about adding min and max as reduction operators for C and C++. However, as you have noted, this has not happened yet. You can do this using the critical construct:

Code: Select all
`int largest = 0;#pragma omp parallel forfor ( int i = 0; i < 1000; i++ ) {  #pragma omp critical  if (data[i] > largest      largest = data[i];}`

This however pretty much serializes your code. Another approach would be to do something like:

Code: Select all
`int largest = 0;#pragma omp parallel forfor ( int i = 0; i < 1000; i++ ) {   if ( data[i] > largest ) {     #pragma omp critical     {       if ( data[i] > largest ) largest = data[i];     }   }}`

This will allow some of your values to be checked without waiting. Another approach would be something like this:

Code: Select all
`int largest = 0;int lp#pragma omp parallel private(lp){  lp = 0;  #pragma omp for  for ( int i = 0; i < 1000; i++) {    if ( data[i] > lp ) lp = data[i];  }  if ( lp > largest ) {    #pragma critical    {      if ( lp > largest ) largest = lp;    }  }}`

This would allow each thread to find the largest value for it's portion of the array and then the only part that needs to be protected with a critical construct is the comparison between the threads. This is for example purposes only and you will need to find out what works best for you.
ejd

Posts: 1025
Joined: Wed Jan 16, 2008 7:21 am