Andrew Dryga
Andrew Dryga

Reputation: 692

MPI data type for 2D array

For hours im trying to send 2D array over MPI to diffrent thread. Code looks like this (i'll leave comments to show tricks that i have already tryed):

Type definition:

// Define datatype
//MPI_Type_contiguous(N, MPI_INT, &mpi_vector);
//MPI_Type_vector(N, N, N, mpi_vector, &mpi_matrix);
//MPI_Type_vector(N, N, N, MPI_INT, &mpi_matrix);
//MPI_Type_contiguous(N, MPI_INTEGER, &mpi_vector);
//MPI_Type_contiguous(N, mpi_vector, &mpi_matrix);
MPI_Type_vector(N, N, 0, MPI_INTEGER, &mpi_matrix);
//MPI_Type_commit(&mpi_vector);
MPI_Type_commit(&mpi_matrix);

Sending and recieving:

int** tmp = new int*[N];
switch(r) {
case T1:
    inputMatrix(tmp, 2);
    MPI_Send(tmp, 1, mpi_matrix, T2, 0, MPI_COMM_WORLD);
    //task_T1();
    break;
case T2:
    //task_T2();
    inputMatrix(tmp, -1);
    MPI_Recv(tmp, 1, mpi_matrix, T1, 0, MPI_COMM_WORLD, &s);
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++) {
            cout << "  " << tmp[i][j];
        }
        cout << endl;
    }
    break;
}

I need to have this done till morning (in 7 hours), i hope smb is able to help me.

Upvotes: 0

Views: 2381

Answers (1)

Hristo Iliev
Hristo Iliev

Reputation: 74355

MPI DOES NOT SUPPORT matrices in which each row is allocated separately, a.k.a. array of pointers to rows. MPI works only with flat arrays where rows are stored consecutively in memory. Use a flat array:

int** tmp = ...

should become

int* tmp = new int[rows*cols];

and then tmp[row][col] should be accessed as tmp[row*cols + col].

You can construct a contiguous type from MPI_INT for a single row and then construct a contiguous type from the previous contiguous type for the whole matrix. You can also construct a single contiguous type of rows*cols MPI_INT elements. The first approach is more flexible as you might need to send individual rows later.

Upvotes: 6

Related Questions