When using MPI_Reduce, I need to deal with some complex data structure. So I need to define my own reduce function by using MPI_Op_create. But the thing is, one or more processes are keep crashing, even on the very simple user defined function, which is all the same to MPI_SUM.
The code is attached below. Note that if I change the parameter in MPI_Reduce from "myOp" to "MPI_SUM", the code works perfectly. So I'm really sure the problem is on the user defined function "myOp". But further debugging in the function "MAX_DataSet" showed the function worked properly with correct result inside. But the program simply cannot correctly execute MPI_Reduce. What is the reason then... Any help is greatly appreciated!
#include <iostream>
#include "mpi.h"
using std::cout;
using std::endl;
void MAX_DataSet(int *in, int *inout, int *len, MPI_Datatype *datatype);
int main(int argc,char **argv)
{
int procSize, procID, x, sum;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &procSize);
MPI_Comm_rank(MPI_COMM_WORLD, &procID);
MPI_Op myOp;
MPI_Op_create((MPI_User_function*)MAX_DataSet, true, &myOp);
if (procID == 0)
x = 15;
else
x = procID;
MPI_Reduce(&x, &sum, 1, MPI_INT, myOp, 0, MPI_COMM_WORLD);
if (procID == 0) // process 0 cannot go here
cout << sum << endl;
MPI_Finalize();
return 0;
}
void MAX_DataSet(int *in, int *inout, int *len, MPI_Datatype *datatype)
{
for (int i = 0; i < *len; i++)
{
*inout = *in + *inout;
in++;
inout++;
}
}