| 1 | #include <stdio.h>
|
|---|
| 2 | #include <stdlib.h>
|
|---|
| 3 | #include <mpi.h>
|
|---|
| 4 |
|
|---|
| 5 | /*
|
|---|
| 6 | ! This program shows how to use MPI_Scatter and MPI_Reduce
|
|---|
| 7 | ! Each processor gets different data from the root processor
|
|---|
| 8 | ! by way of mpi_scatter. The data is summed and then sent back
|
|---|
| 9 | ! to the root processor using MPI_Reduce. The root processor
|
|---|
| 10 | ! then prints the global sum.
|
|---|
| 11 | */
|
|---|
| 12 | /* globals */
|
|---|
| 13 | int numnodes,myid,mpi_err;
|
|---|
| 14 | #define mpi_root 0
|
|---|
| 15 | #ifdef _CIVL
|
|---|
| 16 | $input int count=4;
|
|---|
| 17 | #endif
|
|---|
| 18 | /* end globals */
|
|---|
| 19 |
|
|---|
| 20 | void init_it(int *argc, char ***argv);
|
|---|
| 21 |
|
|---|
| 22 | void init_it(int *argc, char ***argv) {
|
|---|
| 23 | mpi_err = MPI_Init(argc,argv);
|
|---|
| 24 | mpi_err = MPI_Comm_size( MPI_COMM_WORLD, &numnodes );
|
|---|
| 25 | mpi_err = MPI_Comm_rank(MPI_COMM_WORLD, &myid);
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | int main(int argc,char *argv[]){
|
|---|
| 29 | int *myray=NULL,*send_ray=NULL,*back_ray=NULL;
|
|---|
| 30 | #ifndef _CIVL
|
|---|
| 31 | int count;
|
|---|
| 32 | #endif
|
|---|
| 33 | int size,mysize,i,k,j,total,gtotal;
|
|---|
| 34 |
|
|---|
| 35 | init_it(&argc,&argv);
|
|---|
| 36 | /* each processor will get count elements from the root */
|
|---|
| 37 | #ifndef _CIVL
|
|---|
| 38 | count=4;
|
|---|
| 39 | #endif
|
|---|
| 40 | myray=(int*)malloc(count*sizeof(int));
|
|---|
| 41 | /* create the data to be sent on the root */
|
|---|
| 42 | if(myid == mpi_root){
|
|---|
| 43 | size=count*numnodes;
|
|---|
| 44 | send_ray=(int*)malloc(size*sizeof(int));
|
|---|
| 45 | back_ray=(int*)malloc(numnodes*sizeof(int));
|
|---|
| 46 | for(i=0;i<size;i++)
|
|---|
| 47 | send_ray[i]=i;
|
|---|
| 48 | }
|
|---|
| 49 | /* send different data to each processor */
|
|---|
| 50 | mpi_err = MPI_Scatter( send_ray, count, MPI_INT,
|
|---|
| 51 | myray, count, MPI_INT,
|
|---|
| 52 | mpi_root,
|
|---|
| 53 | MPI_COMM_WORLD);
|
|---|
| 54 | /* each processor does a local sum */
|
|---|
| 55 | total=0;
|
|---|
| 56 | for(i=0;i<count;i++)
|
|---|
| 57 | total=total+myray[i];
|
|---|
| 58 | printf("myid= %d total= %d\n",myid,total);
|
|---|
| 59 | /* send the local sums back to the root */
|
|---|
| 60 | mpi_err = MPI_Reduce(&total, >otal, 1, MPI_INT,
|
|---|
| 61 | MPI_SUM,
|
|---|
| 62 | mpi_root,
|
|---|
| 63 | MPI_COMM_WORLD);
|
|---|
| 64 | /* the root prints the global sum */
|
|---|
| 65 | if(myid == mpi_root){
|
|---|
| 66 | printf("results from all processors= %d \n",gtotal);
|
|---|
| 67 | }
|
|---|
| 68 | #ifdef _CIVL
|
|---|
| 69 | free(myray);
|
|---|
| 70 | free(send_ray);
|
|---|
| 71 | free(back_ray);
|
|---|
| 72 | #endif
|
|---|
| 73 | mpi_err = MPI_Finalize();
|
|---|
| 74 | }
|
|---|