I have an array of random numbers and I need to divide it into 4 threads and then find the max number in the array using parallelism. I'm new to working with threads and I have few knowledge of the pragma functions. However, I tried with the next code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <omp.h>
#define N 10000
int searchMax(int *a, int n){
int max, i;
max = a[0];
#pragma omp parallel for
for (i = 0; i < n; i++){
#pragma omp critical
{
if (a[i] > max)
max = a[i];
}
}
return(max);
}
int main(){
int i, arr[N], max;
time_t t;
clock_t tini, tfin;
double tdur;
srand((unsigned) time(&t));
for (i = 0; i < N; i++)
arr[i] = rand();
tini = clock();
max = arr[0];
for (i = 1; i < N; i++)
if (arr[i] > max)
max = arr[i];
tini = clock();
max = searchMax(arr, N);
tfin = clock();
tdur = (double)(tfin - tini) / CLOCKS_PER_SEC;
printf("max number: %d time: %lf\n", max, tdur);
return(0);
}
The thing is that this code only divides the for loop. I don't know how to divide the array into threads and make each of them do the for loop.
You can let OpenMP divide the array into threads for you, no need to worry about -- ok to be fair, OpenMP will divide the array iteration space among the threads not the array itself.
I believe that you can use the reduction clause here as shown below. By using the reduction clause -- in this particular case --, each thread will keep the maximum value (into maxvalue
) and at the end of the parallel region they will choose the maximum value from among the values found by every thread. This way, you can avoid using the critical clause and the #pragma omp parallel for
will distribute the array among threads for you.
int searchMax(int *a, int n){
int maxvalue, i;
#pragma omp parallel for reduction(max: maxvalue)
for (i = 0; i < n; i++)
{
if (a[i] > maxvalue)
maxvalue = a[i];
}
return maxvlue;
}