source: CIVL/examples/mpi/collective/c_ex05.c@ e34d3e8

1.23 2.0 acw/focus-triggers main test-branch
Last change on this file since e34d3e8 was b28f397, checked in by Manchun Zheng <zmanchun@…>, 11 years ago

added more mpi examples

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@2110 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 1.9 KB
Line 
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_Gather
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_Gather. The root processor
10! then prints the global sum.
11*/
12/* globals */
13int numnodes,myid,mpi_err;
14#define mpi_root 0
15/* end globals */
16
17void init_it(int *argc, char ***argv);
18
19void init_it(int *argc, char ***argv) {
20 mpi_err = MPI_Init(argc,argv);
21 mpi_err = MPI_Comm_size( MPI_COMM_WORLD, &numnodes );
22 mpi_err = MPI_Comm_rank(MPI_COMM_WORLD, &myid);
23}
24
25int main(int argc,char *argv[]){
26 int *myray,*send_ray,*back_ray;
27 int count;
28 int size,mysize,i,k,j,total;
29
30 init_it(&argc,&argv);
31/* each processor will get count elements from the root */
32 count=4;
33 myray=(int*)malloc(count*sizeof(int));
34/* create the data to be sent on the root */
35 if(myid == mpi_root){
36 size=count*numnodes;
37 send_ray=(int*)malloc(size*sizeof(int));
38 back_ray=(int*)malloc(numnodes*sizeof(int));
39 for(i=0;i<size;i++)
40 send_ray[i]=i;
41 }
42/* send different data to each processor */
43 mpi_err = MPI_Scatter( send_ray, count, MPI_INT,
44 myray, count, MPI_INT,
45 mpi_root,
46 MPI_COMM_WORLD);
47
48/* each processor does a local sum */
49 total=0;
50 for(i=0;i<count;i++)
51 total=total+myray[i];
52 printf("myid= %d total= %d\n ",myid,total);
53/* send the local sums back to the root */
54 mpi_err = MPI_Gather(&total, 1, MPI_INT,
55 back_ray, 1, MPI_INT,
56 mpi_root,
57 MPI_COMM_WORLD);
58/* the root prints the global sum */
59 if(myid == mpi_root){
60 total=0;
61 for(i=0;i<numnodes;i++)
62 total=total+back_ray[i];
63 printf("results from all processors= %d \n ",total);
64 }
65 mpi_err = MPI_Finalize();
66}
Note: See TracBrowser for help on using the repository browser.