您可以MPI_GATHERV
结合使用MPI_GATHER
来完成此操作。MPI_GATHERV
是的可变版本,MPI_GATHER
它允许根等级从每个发送过程中收集不同数量的元素。但是为了让根等级指定这些数字,它必须知道每个等级包含多少个元素。这可以在此MPI_GATHER
之前使用简单的单个元素来实现。像这样的东西:
// To keep things simple: root is fixed to be rank 0 and MPI_COMM_WORLD is used
// Number of MPI processes and current rank
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *counts = new int[size];
int nelements = (int)vector.size();
// Each process tells the root how many elements it holds
MPI_Gather(&nelements, 1, MPI_INT, counts, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Displacements in the receive buffer for MPI_GATHERV
int *disps = new int[size];
// Displacement for the first chunk of data - 0
for (int i = 0; i < size; i++)
disps[i] = (i > 0) ? (disps[i-1] + counts[i-1]) : 0;
// Place to hold the gathered data
// Allocate at root only
type *alldata = NULL;
if (rank == 0)
// disps[size-1]+counts[size-1] == total number of elements
alldata = new int[disps[size-1]+counts[size-1]];
// Collect everything into the root
MPI_Gatherv(vectordata, nelements, datatype,
alldata, counts, disps, datatype, 0, MPI_COMM_WORLD);
您还应该datatype
为结构注册 MPI 派生数据类型(在上面的代码中)(二进制发送可以工作,但不能移植,并且不能在异构设置中工作)。