Add <p>...</p> wrappers to some .tar.gz reference paragraphs.
[parallel_computing.git] / src / print_tree / global_mpi_operations.c
1 /****************************************************
2 *                                                   *
3 *     demonstration of global MPI operations        *
4 *                                                   *
5 *****************************************************/
6                                 /* Michel Vallieres */
7
8 #include <stdio.h>
9 #include <mpi.h>
10
11 int main ( int argc, char *argv[] )
12 {
13     int    myid, numprocs;
14     double message, local_result, total_result_1, total_result_2;
15
16                                /* join the MPI virtual machine */
17     MPI_Init(&argc, &argv);
18     MPI_Comm_rank(MPI_COMM_WORLD, &myid);
19     MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
20
21                               /* synchronization */
22                               /* all process must reach */
23                               /* here before continuying */
24     MPI_Barrier( MPI_COMM_WORLD );
25     printf( " We are synchronized ( node %d ) \n" , myid );
26
27                               /* an arbitrary message */
28     message = 0;
29     if (myid == 0)
30        message = 5.6788;
31
32                               /* broadcast this message */
33     MPI_Bcast( &message, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD );
34
35                               /* check if message received */
36     printf( " Mynode: %d -- message: %f \n", myid, message );
37
38                               /* process dependent result */
39     local_result = 2.0*myid;
40
41                               /* reduce operations */
42     MPI_Reduce ( &local_result, &total_result_1, 1, MPI_DOUBLE, 
43                                 MPI_MAX, 0, MPI_COMM_WORLD );
44
45     MPI_Reduce ( &local_result, &total_result_2, 1, MPI_DOUBLE, 
46                                 MPI_SUM, 0, MPI_COMM_WORLD );
47
48                               /* only target node - 0 - has the global results */
49     if ( myid == 0 )
50         printf( " Results of global operations: %f %f <-- node 0 has results\n",
51                  total_result_1, total_result_2 );
52
53                               /* reduce operation  */
54                               /* followed by bcast */
55     MPI_Allreduce ( &local_result, &total_result_1, 1, MPI_DOUBLE, 
56                                 MPI_MAX, MPI_COMM_WORLD );
57
58     MPI_Allreduce ( &local_result, &total_result_2, 1, MPI_DOUBLE, 
59                                 MPI_SUM, MPI_COMM_WORLD );
60
61                               /* all nodes have the results */
62     printf( " Results of ALLREDUCE operations (node: %d ): %f %f \n",
63                  myid, total_result_1, total_result_2 );
64
65                               /* end of code */
66     MPI_Finalize();
67     exit(1);
68
69 }