c - MPI_Gatherv : create and collect arrays of variable size (MPI+C)

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

我是 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 元素中,尽管这些元素本来应该不存在。

最佳答案

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

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 的数据。

关于c - MPI_Gatherv : create and collect arrays of variable size (MPI+C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514981/

相关文章:

c - 如何正确排序数组?

c - mifare desfire 中的 ISO14443-4(RATS)

c++ - 在 operator delete[] 中取消析构函数调用

c++ - MPI 代码不适用于 2 个节点,但适用于 1 个

java - 调试 mpi java

multithreading - 在 SGE 上每个节点请求 "M"核心的整数倍

c - 不会打印字符串。字符数组

c - 如何编译目录中的所有 .c 文件并输出不带 .c 扩展名的每个二进制文件

c++ - Valgrind 泄漏检测返回段错误

java.lang.OutOfMemoryError : PermGen space on web app usage 错误