运行 mpirun 时数据类型无效

Invalid datatype when running mpirun

我有一个简单的程序,我想在多台计算机上分散结构,但似乎我定义的数据类型不正确,即使程序编译正常。我有以下代码。

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

typedef struct small_pixel_s {
    double red;
    double green;
    double blue;
} SMALL_PIXEL;

int main(int argc, char **argv) {
    int size, rank;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    SMALL_PIXEL global[8];  
    SMALL_PIXEL local[2];   
    const int root = 0;  

    MPI_Status status;
    MPI_Datatype small_pixel_type;
    MPI_Datatype type[3] = { MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE };
    int blocklen[3] = { 1, 1, 1 };
    MPI_Aint offsets[3];

    offsets[0] = offsetof(SMALL_PIXEL, red);
    offsets[1] = offsetof(SMALL_PIXEL, green);
    offsets[2] = offsetof(SMALL_PIXEL, blue);

    MPI_Type_create_struct(8, blocklen, offsets, type, &small_pixel_type);
    MPI_Type_commit(&small_pixel_type);    

    if (rank == root) {
        for (int i=0; i<7; i++) {
            global[i].red = i;
            global[i].green = i;
            global[i].blue = i;
        }
    }

    MPI_Scatter(global, 2, small_pixel_type,      /* send everyone 2 ints from global */
                local,  2, small_pixel_type,      /* each proc receives 2 ints into local */
                root, MPI_COMM_WORLD);   /* sending process is root, all procs in */
                                         /* MPI_COMM_WORLD participate */
    for (int i=0; i<2; i++) {
        local[i].red = local[i].red + 4;
        local[i].green = local[i].green + 4;
        local[i].blue = local[i].blue + 4;
    }

    MPI_Gather(local,  2, small_pixel_type,      /* everyone sends 2 ints from local */
               global, 2, small_pixel_type,      /* root receives 2 ints each proc into global */
               root, MPI_COMM_WORLD);   /* recv'ing process is root, all procs in */
                                        /* MPI_COMM_WORLD participate */
    if (rank == 0) {
        for (int i=0; i<7; i++) {
            printf("%f\n", global[i].red);
        }
    }

    MPI_Finalize();
    return 0;
}

知道为什么吗?应该如何定义可以分散的struct?

当我运行编程时我得到*** MPI_ERR_TYPE: invalid datatype

MPI_Type_create_struct中,第一个参数是count:

number of blocks (integer) --- also number of entries in arrays array_of_types, array_of_displacements and array_of_blocklengths

在您的情况下,应该是 3,而不是 8。所以改变这一行:

MPI_Type_create_struct(8, blocklen, offsets, type, &small_pixel_type);

对此:

MPI_Type_create_struct(3, blocklen, offsets, type, &small_pixel_type);