TL;DR You can use User-Defined Reduction.
First, instead of:
for(i = 0; i< 10; i++){
if (v[i] > maximo)
maximo = v[i];
b = i + 100;
}
you meant this:
for(i = 0; i< 10; i++){
if (v[i] > maximo){
maximo = v[i];
b = i + 100;
}
}
OpenMP has in-build reduction functions that consider a single target value, however in your case you want to reduce taking into account 2 values the max
and the array index. After OpenMP 4.0 one can create its own reduction functions (i.e., User-Defined Reduction).
First, create a struct to store the two relevant values:
struct MyMax {
int max;
int index;
};
then we need to teach the OpenMP implementation how to reduce it:
#pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)
we set our parallel region accordingly:
#pragma omp parallel for reduction(maximo:myMaxStruct)
for(int i = 0; i< 10; i++){
if (v[i] > myMaxStruct.max){
myMaxStruct.max = v[i];
myMaxStruct.index = i + 100;
}
}
Side Note You do not really need private(i)
, because with the #pragma omp parallel for
the index variable of the for loop will be implicitly private anyway.
All put together:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
struct MyMax {
int max;
int index;
};
int main(void)
{
#pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)
struct MyMax myMaxStruct;
myMaxStruct.max = 0;
myMaxStruct.index = 0;
int v[10] = {2,9,1,3,5,7,1,2,0,0};
#pragma omp parallel for reduction(maximo:myMaxStruct)
for(int i = 0; i< 10; i++){
if (v[i] > myMaxStruct.max){
myMaxStruct.max = v[i];
myMaxStruct.index = i + 100;
}
}
printf("Max %d : Index %d\n", myMaxStruct.max, myMaxStruct.index);
}
OUTPUT:
Max 9 : Index 101
(Index is 101 because you have b = i + 100)