#include "mpi.h" #include int main( int argc, char *argv[]) { int n, myid, numprocs, done; int namelen; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); if (myid == 0) n = 12345; else n = 0; // MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); /* Algorithm 1 */ #if 0 if (myid == 0) { int i; for (i = 1; i < numprocs; i++) MPI_Send(&n, 1, MPI_INT, i, i, MPI_COMM_WORLD); } else { MPI_Recv(&n, 1, MPI_INT, 0, myid, MPI_COMM_WORLD, &status); } #endif /* Algorithm 2 (binary tree) */ done = 1; while (done < numprocs) { if (myid < done) { if (myid + done < numprocs) MPI_Send(&n, 1, MPI_INT, myid + done, 1, MPI_COMM_WORLD); } else if (myid < done + done) MPI_Recv(&n, 1, MPI_INT, myid - done, 1, MPI_COMM_WORLD, &status); done += done; } MPI_Get_processor_name(processor_name,&namelen); fprintf(stderr,"Process %d on %s, n=%d\n", myid, processor_name, n); MPI_Finalize(); return 0; }