MPI_Gatherv可以從不同進程收集大小不同的數據塊,但是在網上看到的都是發送固定大小,偏移量不同的例子,而官網給出的例子,雖然大小可變,但是需要重新定義數據類型,對於連續數據比較麻煩。
下面的代碼按照如下思路
1.每個進程根據進程號初始化一塊數據,發送數據大小與進程號有關(myid+1)
2.首先使用Gather將每個進程要發送數據大小發給root進程,以方便偏移量的計算
3.在root進程裏,計算偏移量
4.調用MPI_Gatherv,(其中發送數據是變量,每個進程不一樣,否則會出現錯誤)
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);
const int n = 100;
int sendBuf[100], *recvBuf;
int *displs, *recvCount;
int root = 0;
//數據初始化,每個進程發送進程號+1的數據
int senddatanum;
for (int i = 0; i < n; i++) {
sendBuf[i] = myid;
senddatanum= myid+1;
}
displs = (int *) malloc(sizeof(int) * p); // displs
recvCount = (int *) malloc(sizeof(int) * p); // send num
//首先將不同進程發送數據塊大小信息獲得,以便後續偏移量的計算
MPI_Gather(&senddatanum, 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];
}
recvBuf = (int *) malloc(p * p * sizeof(int));
memset(recvBuf, 0, sizeof(int) * p * p);
//senddatanum需要與每個進程發送的數據量相等
MPI_Gatherv(sendBuf, senddatanum, MPI_INT, recvBuf, recvCount, displs, MPI_INT,root, MPI_COMM_WORLD);
if (myid == 0) {
for (int i = 0; i < p*p; i++)
printf("%d ", recvBuf[i]);
}
MPI_Finalize();
return 0;
}
Output:
使用5個進程執行之後輸出如下:
1
2
3
4
5
0 1 1 2 2 2 3 3 3 3 4 4 4 4 4 0 0 0 0 0 0 0 0 0 0