| 1 | #include "mpi.h"
|
|---|
| 2 | #include <stdio.h>
|
|---|
| 3 | #include <stdlib.h>
|
|---|
| 4 | #include <assert.h>
|
|---|
| 5 | #define SIZE 4
|
|---|
| 6 |
|
|---|
| 7 | int main (int argc, char *argv[])
|
|---|
| 8 | {
|
|---|
| 9 | int numtasks, rank, sendcount, recvcount, source;
|
|---|
| 10 | float sendbuf[SIZE * SIZE] = {
|
|---|
| 11 | 1.0, 2.0, 3.0, 4.0,
|
|---|
| 12 | 5.0, 6.0, 7.0, 8.0,
|
|---|
| 13 | 9.0, 10.0, 11.0, 12.0,
|
|---|
| 14 | 13.0, 14.0, 15.0, 16.0};
|
|---|
| 15 | float recvbuf[SIZE];
|
|---|
| 16 |
|
|---|
| 17 | MPI_Init(&argc,&argv);
|
|---|
| 18 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 19 | MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
|
|---|
| 20 |
|
|---|
| 21 | if (numtasks == SIZE) {
|
|---|
| 22 | source = 1;
|
|---|
| 23 | sendcount = SIZE;
|
|---|
| 24 | recvcount = SIZE;
|
|---|
| 25 | if(source == rank){
|
|---|
| 26 | // Locally assign recvbuf for root process,
|
|---|
| 27 | // then using MPI_INPLACE for scattring.
|
|---|
| 28 | for(int i=0; i<SIZE; i++)
|
|---|
| 29 | recvbuf[i] = *(sendbuf + rank * SIZE + i);
|
|---|
| 30 | MPI_Scatter(sendbuf,sendcount,MPI_FLOAT,MPI_IN_PLACE,recvcount,
|
|---|
| 31 | MPI_FLOAT,source,MPI_COMM_WORLD);
|
|---|
| 32 | }
|
|---|
| 33 | else
|
|---|
| 34 | MPI_Scatter(sendbuf,sendcount,MPI_FLOAT,recvbuf,recvcount,
|
|---|
| 35 | MPI_FLOAT,source,MPI_COMM_WORLD);
|
|---|
| 36 |
|
|---|
| 37 | printf("rank= %d Results: %f %f %f %f\n",rank,recvbuf[0],
|
|---|
| 38 | recvbuf[1],recvbuf[2],recvbuf[3]);
|
|---|
| 39 | //add assertions
|
|---|
| 40 | for(int i=0; i<SIZE; i++)
|
|---|
| 41 | assert(recvbuf[i] == *(sendbuf + SIZE * rank + i));
|
|---|
| 42 | }
|
|---|
| 43 | else
|
|---|
| 44 | printf("Must specify %d processors. Terminating.\n",SIZE);
|
|---|
| 45 |
|
|---|
| 46 | MPI_Finalize();
|
|---|
| 47 | }
|
|---|