I am pretty new in MPI and trying to get understand the sense by writing a simple C program. All I want to do is to split an array and send blocks to N processors. So, each processor will find local mins in their blocks. Then the program (in root or somewhere else) finds the global min.
I studied on MPI_Send
, MPI_Isend
, or MPI_Bcast
functions but a little bit confused in where to use one instead of another. I need some tips for the general structure of my program:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define N 9 // array size
int A[N] = {0,2,1,5,4,3,7,6,8}; // this is a dummy array
int main(int argc, char *argv[]) {
int i, k = 0, size, rank, source = 0, dest = 1, count;
int tag = 1234;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
count = N/(size-1); // think size = 4 for this example
int *tempArray = malloc(count * sizeof(int));
int *localMins = malloc((size-1) * sizeof(int));
if (rank == 0) {
for(i=0; i<size; i+=count)
{
// Is it better to use MPI_Isend or MPI_Bcast here?
MPI_Send(&A[i], count, MPI_INT, dest, tag, MPI_COMM_WORLD);
printf("P0 sent a %d elements to P%d.\n", count, dest);
dest++;
}
}
else {
for(i=0; i<size; i+=count)
{
MPI_Recv(tempArray, count, MPI_INT, 0, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
localMins[k] = findMin(tempArray, count);
printf("Min for P%d is %d.\n", rank, localMins[k]);
k++;
}
}
MPI_Finalize();
int gMin = findMin(localMins, (size-1)); // where should I assign this
printf("Global min: %d\n", gMin); // and where should I print the results?
return 0;
}
There could be multiple errors on my code and sorry for cannot specify an exact problem here. Thanks for any suggestion.