MPI在MPI_Type_struct中发送和接收指针

时间:2019-04-24 16:55:58

标签: mpi mpich

我想使用MPI_Type_struct发送一组数据,其中一个是指向数组的指针(因为我将要使用的矩阵将非常大,因此我需要执行malloc)。我看到的问题是除矩阵外,所有数据均正确传递。我知道可以通过指针传递矩阵,因为如果只发送矩阵的指针,则会观察到正确的结果。

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

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

    MPI_Init(&argc, &argv);
    int size, rank;
    int m,n;
    m=n=2;

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

    typedef struct estruct
    {
        float *array;
        int sizeM, sizeK, sizeN, rank_or;
    } ;

    struct estruct kernel, server;

    MPI_Datatype types[5] = {MPI_FLOAT, MPI_INT,MPI_INT,MPI_INT,MPI_INT};
    MPI_Datatype newtype;
    int lengths[5] = {n*m,1,1,1,1};
    MPI_Aint displacements[5];
    displacements[0] = (size_t) & (kernel.array[0]) - (size_t)&kernel;
    displacements[1] = (size_t) & (kernel.sizeM) - (size_t)&kernel;
    displacements[2] = (size_t) & (kernel.sizeK) - (size_t)&kernel;
    displacements[3] = (size_t) & (kernel.sizeN) - (size_t)&kernel;
    displacements[4] = (size_t) & (kernel.rank_or) - (size_t)&kernel;


    MPI_Type_struct(5, lengths, displacements, types, &newtype);
    MPI_Type_commit(&newtype);

    if (rank == 0)
    {
        kernel.array  = (float *)malloc(m * n * sizeof(float));
        for(int i = 0; i < m*n; i++) kernel.array[i] = i;
        kernel.sizeM = 5;
        kernel.sizeK = 5;
        kernel.sizeN = 5;
        kernel.rank_or = 5;
        MPI_Send(&kernel, 1, newtype, 1, 0, MPI_COMM_WORLD);
    }
    else
    {
        server.array  = (float *)malloc(m * n * sizeof(float));
        MPI_Recv(&server, 1, newtype, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

        printf("%i \n", server.sizeM);
        printf("%i \n", server.sizeK);
        printf("%i \n", server.sizeN);
        printf("%i \n", server.rank_or);
        for(int i = 0; i < m*n; i++) printf("%f\n",server.array[i]);
    }

    MPI_Finalize();
}

假设只执行两个进程,我希望rank = 1的进程接收并在屏幕上显示矩阵的正确元素(其他元素收到良好),但实际输出为:

5
5
5
5
0.065004
0.000000
0.000000
0.000000

===================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   PID 26206 RUNNING AT pmul
=   EXIT CODE: 11
=   CLEANING UP REMAINING PROCESSES
=   YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
===================================================================================
YOUR APPLICATION TERMINATED WITH THE EXIT STRING: Segmentation fault (signal 11)
This typically refers to a problem with your application.
Please see the FAQ page for debugging suggestions

我希望有人能帮助我。

0 个答案:

没有答案