this is my first time ever using MPI (I am also quite new to C++ as well) and I am trying to do this challenge for a course and I am very confused. I think I have to be overthinking it, but basically I have to broadcast the given array to each node, have each thread (4) sum the array, and then reduce the result. What I believe I have left to do is just the summation section, but I cannot figure out how to do this in parallel after the MPI broadcast, as most examples online use send and receive and are also only one-dimensional. I need to add this under the comment // Need two lines of code here to sum the array (rows and columns), what is the proper way to do this? Any help would be greatly appreciated, thanks!
P.S. A lot of the code was provided from the instructor, but I did alter a few things here and there so feel free to correct anything else you see wrong or poorly-coded.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int procNum, procRank, m, n;
int sumProc = 0, sumAll = 0;
int** arr;
MPI_Status status;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &procNum);
MPI_Comm_rank(MPI_COMM_WORLD, &procRank);
if (procRank == 0) {
&m = 4;
&n = 5;
}
MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
int sample_array[4][5] = {
{50, 55, 62, 70, 85},
{35, 42, 45, 47, 49},
{32, 33, 36, 37, 38},
{25, 30, 30, 35, 30}
};
arr = new int*[m];
for (int i = 0; i < m; i++) {
arr[i] = new int[n];
}
if (procRank == 0) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sample_array[i][j];
printf("%i ", arr[i][j]);
}
printf("\n");
}
}
for (int i = 0; i < m; i++) {
MPI_Bcast(arr[i], m*n, MPI_INT, 0, MPI_COMM_WORLD);
{
// Need two lines of code here to sum the array (rows and columns)
sumProc += 1;
MPI_Reduce(&sumProc, &sumAll, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (procRank == 0) {
printf("sumAll = %i \n", sumAll);
}
delete *arr;
MPI_Finalize();
return 0;
}