首页 > 解决方案 > MPI 发送和接收结构体

问题描述

我目前正在努力发送和接收以下包含通过 MPI 用 c 编写的二维数组的结构。

结构如下:

typedef struct a_s {
    double array[3][3];
    int err;
} a;

我应该怎么办?


更新:

在 C 中的结构序列化和通过 MPI 传输的帮助下,我编辑了以下代码以实现我的目的。

typedef struct a_s {
    double array[3][3];
    int err;
} a;

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

    // Initialize the MPI environment
    MPI_Init(NULL, NULL);

    // Get the number of processes
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    // Get the rank of the process
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    // Get the name of the processor
    char processor_name[MPI_MAX_PROCESSOR_NAME];
    int name_len;
    MPI_Get_processor_name(processor_name, &name_len);

    // Print off a hello world message
    printf("Hello world from processor %s, rank %d"
           " out of %d processors\n",
           processor_name, world_rank, world_size);

    int i, x;


    const int nitems = 2;
    int blocklenghts[2] = {3*3, 1};
    MPI_Datatype types[2] = {MPI_DOUBLE, MPI_INT};
    MPI_Datatype mpi_send_data;
    MPI_Aint offsets[2];

    offsets[0] = offsetof(a, array);
    offsets[1] = offsetof(a, err);

    MPI_Type_create_struct(nitems, blocklenghts, offsets, types, &mpi_send_data);
    MPI_Type_commit(&mpi_send_data);

    a mydata;

    for (i = 0; i < 3; i++){
        for (x = 0; x < 3; ++x)
        {
            mydata.array[i][x] = 0;
        }
    }

    mydata.err = 0;

    if(world_rank != 0){

        for (i = 0; i < 3; i++){
            for (x = 0; x < 3; ++x)
            {
                mydata.array[i][x] = world_rank;
            }
        }

        mydata.err = 10;
        MPI_Send(&mydata, 1, mpi_send_data, 0, 0, MPI_COMM_WORLD);

    } else {

        MPI_Recv(&mydata, 1, mpi_send_data, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

        for (i = 0; i < 3; i++){
            for (x = 0; x < 3; ++x)
            {
                printf("%f ", mydata.array[i][x]);
            }

            printf("\n");
        }

        printf("%d \n", mydata.err);

    }

    // Finalize the MPI environment.
    MPI_Finalize();
}

标签: cmpi

解决方案


推荐阅读