Using MPI_Type_struct datatypes to share data

 

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

int main( argc, argv )
int argc;
char **argv;
{
    int          rank;
    struct {
           int a;
           int b;
           double c;
           double d;
           double e;
           double f;
           } value;

    MPI_Datatype mystruct;
    int          blocklens[2];
    MPI_Aint     indices[2], extent;
    MPI_Datatype old_types[2];

    MPI_Init( &argc, &argv );

    MPI_Comm_rank( MPI_COMM_WORLD, &rank );

    /* One value of each type */
    blocklens[0] = 2;
    blocklens[1] = 4;
    /* The base types */
    old_types[0] = MPI_INT;
    old_types[1] = MPI_DOUBLE;
    /* The locations of each element */


    MPI_Type_extent(MPI_INT, &extent); /* instead of MPI_Address to obtain displacement */
    indices[0] = 0;
    indices[1] = 2*extent;
    MPI_Type_struct( 2, blocklens, indices, old_types, &mystruct );
    MPI_Type_commit( &mystruct );

    do {
        if (rank == 0)
            scanf( "%d %d %lf %lf %lf %lf", &value.a,&value.b,&value.c,&value.d,&value.e,&value.f);

        MPI_Bcast( &value, 1, mystruct, 0, MPI_COMM_WORLD );

        printf("Process %d got %d %d %lf %lf %lf and %lf
", rank, value.a,value.b,value.c,value.d,value.e,val
ue.f);
    } while (value.a >= 0);

    /* Clean up the type */
    MPI_Type_free( &mystruct );
    MPI_Finalize( );
    return 0;
}