0

I want to using MPI MPI_File_read_all to read a file input.txt which contains binary integers 0,1,2,...,1000.

In my implementation, I use MPI_Type_create_subarray to create a 5*5 subarray mysub out of a 10*10 array. Hoping to read following matrix out from file.

0       1       2       3       4
10      11      12      13      14
20      21      22      23      24
30      31      32      33      34
40      41      42      43      44

But my program read following integers instead (also cause segmentation error in the final stage of the program):

0       1       2       3       4
22002   -1984077600     22002   0       0
10      11      12      13      14
0       0       0       0       0
20      21      22      23      24

Here is my code

#include<iostream>                                                                                                                                               
#include<mpi.h>                                                                                                                                                  
using namespace std;  

void read_subarray(const MPI_File &fh, int rank) {
    int bigsize = 10, subsize = 5;
    int **A = new int*[subsize];
    int *buf = new int[subsize*subsize];
    for (int i=0;i<subsize;i++) A[i] = &buf[subsize*i];

    int bigsizes[] = {bigsize, bigsize};
    int subsizes[] = {subsize, subsize};
    int offsets[] = {0, 0};

    MPI_Datatype mysub;
    MPI_Type_create_subarray(2, bigsizes, subsizes, offsets, MPI_ORDER_C, MPI_INT, &mysub);
    MPI_Type_commit(&mysub);

    MPI_Status status;
    int disp = 0;
    MPI_File_set_view(fh, disp, MPI_INT, mysub, "native", MPI_INFO_NULL);
    MPI_File_read_all(fh, &(A[0][0]), 1, mysub, &status);

    cout<<"array for "<<rank<<endl;
    for (int i=0;i<subsize; i++) {
        for (int j=0;j<subsize; j++) 
            cout<<A[i][j]<<"\t"; 
        cout<<endl;
    }


    MPI_Type_free(&mysub);
}

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

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

    MPI_File fh;
    MPI_File_open(MPI_COMM_WORLD, "./input.txt", MPI_MODE_RDONLY, MPI_INFO_NULL, &fh);

    read_subarray(fh, rank);

    MPI_File_close(&fh);
    MPI_Finalize();
    return 0;
}
Toby Mao
  • 105
  • 1
  • 1
  • 10
  • 1
    What if you `MPI_File_read_all(fh, &(A[0][0]), subsize * subsize, MPI_INT, &status);`? – Gilles Gouaillardet Jan 25 '21 at 11:28
  • @GillesGouaillardet It works. Maybe I have some misunderstanding on `MPI_File_read_all`. Thanks! – Toby Mao Jan 25 '21 at 11:48
  • the datatype passed to `MPI_File_set_view()` is for the data in the file (e.g. a sub-matrix). the data you read into is a dense `int[subsize][subsize]` matrix, so you you have to passed `count=subsize*subsize` and `type=MPI_INT` to `MPI_File_read()` – Gilles Gouaillardet Jan 25 '21 at 12:03

0 Answers0