- include <stdio.h>
- #include <stdlib.h>
- #include <mpi.h>
- int main(int argc, char *argv[])
- {
- int rank, size;
- double message, local_result, total_result_1, total_result_2;
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- MPI_Comm_size(MPI_COMM_WORLD, &size);
- /* Synchronization.
- * All process must reach here before continuing. */
- MPI_Barrier(MPI_COMM_WORLD);
- /* Synchronize again to ensure the "synchronized" messages are contiguous. */
- MPI_Barrier(MPI_COMM_WORLD);
- /* An arbitrary message */
- message = 0;
- if (rank == 0)
- message = 5.6789;
- /* Broadcast this message */
- MPI_Bcast(&message, 1, MPI_DOUBLE, 0 /* root */ , MPI_COMM_WORLD);
- /* Check if message received */
- /* Process dependent result */
- local_result = 2.0 * rank;
- /* Reduce operations */
- MPI_Reduce(&local_result, &total_result_1, 1, MPI_DOUBLE,
- MPI_MAX, 0 /* target_process */ , MPI_COMM_WORLD);
- MPI_Reduce(&local_result, &total_result_2, 1, MPI_DOUBLE,
- MPI_SUM, 0 /* target_process */ , MPI_COMM_WORLD);
- /* Only target node 0 has the global results */
- if (rank == 0)
- ("results of global operations: %f %f <-- node 0 has results\n",
- total_result_1, total_result_2);
- /* Reduce operation followed by bcast. */
- MPI_Allreduce(&local_result, &total_result_1, 1, MPI_DOUBLE,
- MPI_MAX, MPI_COMM_WORLD);
- MPI_Allreduce(&local_result, &total_result_2, 1, MPI_DOUBLE,
- MPI_SUM, MPI_COMM_WORLD);
- /* All nodes have the results */
- rank, total_result_1, total_result_2);
- /* Clean up and exit */
- MPI_Finalize();
- }
Raw Paste