将自定义数据类型输出到文件

时间:2014-04-22 22:48:13

标签: c++ parallel-processing mpi openmpi hpc

给定结构Pixel及其等效MPI_Type mpiPixel我创建一个像素数组并将其写入文件。一切都正常运行,除了,文件中的输出以某种位模式结束(被解释为整数)。该文件以二进制形式输出,因此我使用hexdump -v -e '7/4 "%10d "' -e '"\n"' pixelsx

查看它是否正确写入

代码

struct Pixel
{
    int red; int green; int blue;

    Pixel() {}

    Pixel(int r, int g, int b)
    {
        red = r; green = g; blue = b;
    }
};


int main(int argc, char **argv)
{
    int rank, size;
    MPI_File   file;
    MPI_Offset offset;
    MPI_Status status;
    MPI_Datatype mpiPixel;

    Pixel pixels[10];

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

    /* fill local data */
    for (int i = 0; i < 10; i++)
        pixels[i] = Pixel(i, i, i);

    int blockcounts[1];
    MPI_Aint offsets[1];
    MPI_Datatype oldtypes[1];

    //Pixel Description {starting pos, element count, element type}
    offsets[0] = 0;
    blockcounts[0] = 3;
    oldtypes[0] = MPI_INT;

    /* Now define structured type and commit it */
    MPI_Type_struct(1, blockcounts, offsets, oldtypes, &mpiPixel);
    MPI_Type_commit(&mpiPixel);

    /* open the file, and set the view */
    MPI_File_open(MPI_COMM_WORLD, "pixels",
                  MPI_MODE_CREATE | MPI_MODE_WRONLY,
                  MPI_INFO_NULL, &file);

    MPI_File_seek(file, 0, MPI_SEEK_SET);
    MPI_File_set_view(file, 0,  MPI_CHAR, mpiPixel, "native", MPI_INFO_NULL);
    MPI_File_write_all(file, pixels, 10, mpiPixel, &status);
    MPI_File_close(&file);

    MPI_Finalize();
    return 0;
}

输出

     0          0          0          1          1          1          2
     2          2          3          3          3          4          4
     4          5          5          5          6          6          6
     7          7          7          8          8          8          9
     9          9    4228656          0          0          0    4228656
     0          0          0 -1795965243      32585   

不应该存在的那条线(如果我没有弄错的话)是

4228656          0          0          0    4228656         0          0          0 -1795965243      32585

为什么后者会在文件中打印出来。这是一个内存分配问题(数组?)?

P.S。代码仅使用一个进程运行。原因是我首先需要让写功能正常工作。然后,为其他进程添加偏移量

1 个答案:

答案 0 :(得分:1)

MPI数据类型根本不符合C ++结构。您的Pixel结构包含三个int元素。您为四个float元素注册MPI数据类型,并使用它将结构数组写入文件。由于intfloat恰好在大多数32位和64位体系结构上具有相同的大小,并且由于在结构元素之间没有添加填充,因此MPI最终读取(4*sizeof(float) - sizeof(Pixel))*10 = 40个字节pixels数组的结尾。这在文件内容中显示为10(40/4)个附加随机值。