如果需要将一个进程中的数据分发到不同进程,可以使用这个函数
而每个进程如果需要的数目不同,则需要如下操作:
1.首先根进程得到每个进程需要的数目(通过组收集gather)
2.然后计算发送的数据不同的偏移(根据每个进程需要的数目计算)
3.组分发
int main(int argc, char *argv[])
{
int myid; //process id number
int p; //number of process
MPI_Init(&argc, &argv); //parallel init
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &p);
int *receiveBuf, *recvCount;
receiveBuf = (int *) malloc((myid + 1) * sizeof(int));
memset(receiveBuf, 0, (myid + 1) * sizeof(int));
int *stride, *displs, *scounts;
stride = (int *) malloc(p * sizeof(int));
displs = (int *) malloc(p * sizeof(int));
scounts = (int *) malloc(p * sizeof(int));
int *sendbuf;
int receivedatanum = myid + 1;
recvCount = (int *) malloc(sizeof(int) * p); // send num
int root = 0;
MPI_Gather(&receivedatanum, 1, MPI_INT, recvCount, 1, MPI_INT, root,
MPI_COMM_WORLD);
if (!myid) {
for (int i = 0; i < p; i++)
printf("%d \n", recvCount[i]);
displs[0] = 0;
displs[1] = displs[0] + recvCount[0];
displs[2] = displs[1] + recvCount[1];
displs[3] = displs[2] + recvCount[2];
displs[4] = displs[3] + recvCount[3];
sendbuf = (int *) malloc(p * p * sizeof(int));
memset(sendbuf, 0, sizeof(int) * p * p);
for (int i = 0; i < p * p; i++)
sendbuf[i] = i;
}
MPI_Scatterv(sendbuf, recvCount, displs, MPI_INT, receiveBuf,receivedatanum, MPI_INT, root, MPI_COMM_WORLD);
for (int i = 0; i < myid + 1; i++) {
printf("%d %d %d\n", receiveBuf[i], myid, i);
}
MPI_Finalize();
}
输出:
使用5个进程跑出如下结果:
//表明gather成功执行
1
2
3
4
5
//第一列是实际数据,第二列是进程号,第三列是该进程号里的第n个数
0 0 0
3 2 0
4 2 1
5 2 2
6 3 0
7 3 1
8 3 2
9 3 3
10 4 0
11 4 1
12 4 2
13 4 3
14 4 4
1 1 0
2 1 1
0号进程得到一个数据,1号进程得到2个数据,2号进程得到3个数据。。。