source: CIVL/examples/mpi/collective/c_ex06.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.8 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_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 */
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,gtotal;
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/* each processor does a local sum */
48 total=0;
49 for(i=0;i<count;i++)
50 total=total+myray[i];
51 printf("myid= %d total= %d\n ",myid,total);
52/* send the local sums back to the root */
53 mpi_err = MPI_Reduce(&total, &gtotal, 1, MPI_INT,
54 MPI_SUM,
55 mpi_root,
56 MPI_COMM_WORLD);
57/* the root prints the global sum */
58 if(myid == mpi_root){
59 printf("results from all processors= %d \n ",gtotal);
60 }
61 mpi_err = MPI_Finalize();
62}
Note: See TracBrowser for help on using the repository browser.