1 /****************************************************
3 * demonstration of global MPI operations *
5 *****************************************************/
11 int main ( int argc, char *argv[] )
14 double message, local_result, total_result_1, total_result_2;
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);
22 /* all process must reach */
23 /* here before continuying */
24 MPI_Barrier( MPI_COMM_WORLD );
25 printf( " We are synchronized ( node %d ) \n" , myid );
27 /* an arbitrary message */
32 /* broadcast this message */
33 MPI_Bcast( &message, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD );
35 /* check if message received */
36 printf( " Mynode: %d -- message: %f \n", myid, message );
38 /* process dependent result */
39 local_result = 2.0*myid;
41 /* reduce operations */
42 MPI_Reduce ( &local_result, &total_result_1, 1, MPI_DOUBLE,
43 MPI_MAX, 0, MPI_COMM_WORLD );
45 MPI_Reduce ( &local_result, &total_result_2, 1, MPI_DOUBLE,
46 MPI_SUM, 0, MPI_COMM_WORLD );
48 /* only target node - 0 - has the global results */
50 printf( " Results of global operations: %f %f <-- node 0 has results\n",
51 total_result_1, total_result_2 );
53 /* reduce operation */
54 /* followed by bcast */
55 MPI_Allreduce ( &local_result, &total_result_1, 1, MPI_DOUBLE,
56 MPI_MAX, MPI_COMM_WORLD );
58 MPI_Allreduce ( &local_result, &total_result_2, 1, MPI_DOUBLE,
59 MPI_SUM, MPI_COMM_WORLD );
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 );