/*

 * gather_scatter.c

 * Demonstrate MPI_Allgather and MPI_Scatter

 *  Created on: 31 Οκτ 2011

 *      Author: kostas

 */

 

 

#include "mpi.h"

#include <stdio.h>

#include <math.h>

 

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

       int procs, rank;

       int i;

       int localA[2], A[10];

       int B[10], localB[2];

 

       MPI_Init(&argc, &argv);

       MPI_Comm_size(MPI_COMM_WORLD, &procs);

       MPI_Comm_rank(MPI_COMM_WORLD, &rank);

 

       if (procs > 5) {

              return 0;

       }

 

       /*

        * A[] = collects all localA[] from the other processes using Allgather

        * B[] = scatters to all localB[] of the other processes using Scatter

        * Initialize A[] = zero

        */

       for (i=0; i<10; i++) {

              A[i] = 0;

              B[i] = 2001+i;

       }

 

       /* Initialize array localA[] for each process

        * P0: localA = [101, 102, ...]

        * P1: localA = [201, 202, ...]

        * P2: localA = [301, 302, ...]

        * etc

        */

       for (i=0; i<2; i++) {

              localA[i] = 100*(rank+1)+(i+1);

       }

 

       /* AllGather: localA --> A */

       MPI_Allgather(localA, 2, MPI_INT, A, 2, MPI_INT, MPI_COMM_WORLD);

 

       /* Scatter: B --> localB */

       MPI_Scatter(B, 2, MPI_INT, localB, 2, MPI_INT, 0, MPI_COMM_WORLD);

 

       /* Print A for each process

        * Ie. the result of MPI_Allgather */

       for (i=0; i<10; i++) {

              printf("P:%d A[%d]=%d  ", rank, i, A[i]);

              fflush(stdout);

              MPI_Barrier(MPI_COMM_WORLD);

              if (rank==0) {

                     printf("\n");

                     fflush(stdout);

              }

       }

 

       /* Print localB for each process

        * Ie. the result of MPI_Scatter */

       for (i=0; i<2; i++) {

              printf("P:%d locB[%d]=%d  ", rank, i, localB[i]);

              fflush(stdout);

              MPI_Barrier(MPI_COMM_WORLD);

              if (rank==0) {

                     printf("\n");

                     fflush(stdout);

              }

       }

 

       MPI_Finalize();

 

       return(0);

}