如果需要將一個進程中的數據分發到不同進程,可以使用這個函數
而每個進程如果需要的數目不同,則需要如下操作:
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個數據。。。