在使用 MPI_Reduce 时,我需要处理一些复杂的数据结构。所以我需要使用 MPI_Op_create 来定义我自己的 reduce 函数。但问题是,一个或多个进程一直在崩溃,即使在非常简单的用户定义函数上也是如此,这与 MPI_SUM 完全相同。
代码附在下面。请注意,如果我将 MPI_Reduce 中的参数从“myOp”更改为“MPI_SUM”,则代码可以完美运行。所以我很确定问题出在用户定义的函数“myOp”上。但在函数“MAX_DataSet”中进一步调试表明该函数正常工作,内部结果正确。但是程序根本无法正确执行 MPI_Reduce。那是什么原因......非常感谢任何帮助!
#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++;
}
}