MPI_Gatherv 的使用 发送接收不同大小的数据块

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章