【问题标题】:MPI_Gatherv: create and collect arrays of variable size (MPI+C)MPI_Gatherv:创建和收集可变大小的数组(MPI+C)
【发布时间】:2018-11-04 00:20:11
【问题描述】:

我是 MPI 的新手,我正在尝试并行管理不同大小的数组,然后将它们传递给主线程,但到目前为止没有成功。

我知道了

MPI_Gatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
        void *recvbuf, const int *recvcounts, const int *displs,
        MPI_Datatype recvtype, int root, MPI_Comm comm)

在这种情况下是要走的路。

这是我的示例代码,由于内存问题(我认为)不起作用。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>

int main (int argc, char *argv[]) {

MPI_Init(&argc, &argv);
int world_size,*sendarray;
int rank, *rbuf=NULL, count;
int *displs=NULL,i,*rcounts=NULL;

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);

if(rank==0){
    rbuf = malloc(10*sizeof(int));
    displs = malloc(world_size*sizeof(int));
    rcounts=malloc(world_size*sizeof(int));
    rcounts[0]=1;
    rcounts[1]=3;
    rcounts[2]=6;

    displs[0]=1;
    displs[1]=3;
    displs[2]=6;

    sendarray=malloc(1*sizeof(int));
    for(int i=0;i<1;i++)sendarray[i]=1;
    count=1;
}

if(rank==1){
    sendarray=malloc(3*sizeof(int));
    for(int i=0;i<3;i++)sendarray[i]=2;
    count=3;
}

if(rank==2){
    sendarray=malloc(6*sizeof(int));
    for(int i=0;i<6;i++)sendarray[i]=3;
    count=6;
}
MPI_Barrier(MPI_COMM_WORLD);


MPI_Gatherv(sendarray, count, MPI_INT, rbuf, rcounts,
            displs, MPI_INT, 0, MPI_COMM_WORLD);

if(rank==0){
    int SIZE=10;
    for(int i=0;i<SIZE;i++)printf("(%d) %d ",i, rbuf[i]);

    free(rbuf);
    free(displs);
    free(rcounts);
}

if(rank!=0)free(sendarray);
MPI_Finalize();

}

具体来说,当我运行它时,我得到了

(0) 0 (1) 1 (2) 0 (3) 2 (4) 2 (5) 2 (6) 3 (7) 3 (8) 3 (9) 3

不是这样的

(0) 1 (1) 2 (2) 2 (3) 2 (4) 3 (5) 3 (6) 3 (7) 3 (8) 3 (9) 3

这是为什么呢?

更有趣的是,似乎缺失的元素存储在 rbuf 的第 11 和 12 个元素中,尽管这些元素原本应该不存在。

【问题讨论】:

    标签: c memory-leaks mpi communication dynamic-memory-allocation


    【解决方案1】:

    您的程序非常接近工作。如果您更改这些行:

    displs[0]=1;
    displs[1]=3;
    displs[2]=6;
    

    到这里:

    displs[0]=0;
    displs[1]=displs[0]+rcounts[0];
    displs[2]=displs[1]+rcounts[1];
    

    您将获得预期的输出。变量displs 是接收缓冲区的偏移量,用于放置来自进程 i 的数据。

    【讨论】:

    猜你喜欢
    • 2016-10-29
    • 2019-06-28
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多