justin waugh
justin waugh

Reputation: 895

How to send nested structure using MPI_Datatype in MPI using C

I am trying to use MPI_Datatype to send the below structure but the MPI_Send crashes while sending the structure. I am wondering how to handle this situation. Here is the code I have written to define new MPI data-type:

   typedef struct
    {
       double x;
       double y;
    } vertex;

   typedef struct
   {
        int num_vertices;
        vertex vertex[2];
   } vertex_list;


       MPI_Datatype vertexType;
        MPI_Type_contiguous(2,MPI_DOUBLE,&vertexType);
        MPI_Type_commit(&vertexType);

      MPI_Datatype vertexListType;
        MPI_Datatype typev[3] = {MPI_INT, vertexType, MPI_UB};
        int blocklenv[3] = {1, 2, 1};
        MPI_Aint dispv[3];
        /* compute displacements of structure components */
        MPI_Address( vertexl, dispv);
        MPI_Address( vertexl[0].vertex, dispv+1);
        MPI_Address(  vertexl+1, dispv+2);
        base = dispv[0];

        for (i=0; i <3; i++)
         dispv[i] -= base;

        /* build datatype describing structure */
        MPI_Type_struct( 3, blocklenv, dispv, typev, &vertexListType);
        MPI_Type_commit(&vertexListType);

https://docs.google.com/document/d/1OQFtx0ClkKQx7X91BlVgiizs5D9jShhtgsKafrgC7hk/edit?hl=en

Upvotes: 1

Views: 2964

Answers (1)

Captain Head
Captain Head

Reputation: 343

I'm not sure your structs are going to work the way you're intending here, but I can share my experience with sending structs with MPI_Send.

Rather than creating an explicit MPI datatype it's possible to simply send the struct itself since all of its contents are in a contiguous piece of memory. The trick is providing the correct size and datatype for the MPI_Send operation.

Using your structs, here's what I've done in the past (assuming variable vertex_list list has already been defined):

MPI_Send(&list, sizeof(vertex_list), MPI_BYTE, <rankToSendTo>, <tagInteger>, <comm>);

So the data buffer to be sent is a pointer to the list struct, the size of the buffer is the size of a vertex_list in bytes and the MPI datatype is simply bytes.

On the receiving end, you just need to supply a vertex_list reference as the receiving buffer:

vertex_list receiveList;
MPI_Recv(&receiveList, sizeof(vertex_list), MPI_BYTE, <rankOfSender>, <tagInteger>, <comm>, <status>);

Hope that helps!

Upvotes: 3

Related Questions