#include #include #include #include #define NOT_DONE 0 #define DONE 1 #define NO_TAG 2 #define WORK_PER_SLAVE 100000 int main(int argc, char **argv) { int server,slave,total_slaves; int total_rand,r,i,tag; int destination,sum,sum_slaves; int size,rank,slave_rank; double average; MPI_Comm world,slaves; MPI_Status status; /* Initializations */ MPI_Init(&argc,&argv); world=MPI_COMM_WORLD; MPI_Comm_size(world,&size); if( size < 2) { printf("\nUnable to run in less than 2 processes...\n\n"); MPI_Abort(world,1); } MPI_Comm_rank(world,&rank); /* Define slave communicator */ server=0; slave=( rank == server ); MPI_Comm_split(world,slave,0,&slaves); /* Master */ if( rank == server ) { total_slaves=size-1; total_rand=0; srand(time(NULL)); do { MPI_Recv(&r,1,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,world,&status); tag=status.MPI_TAG; if( tag != DONE ) { r=1 + (int)( 10.0 * rand() / ( RAND_MAX + 1.0 ) ); destination=status.MPI_SOURCE; MPI_Send(&r,1,MPI_INT,destination,NO_TAG,world); ++total_rand; } else --total_slaves; } while(total_slaves); MPI_Barrier(world); MPI_Recv(&sum,1,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,world,&status); average=(double)sum/(double)total_rand; printf("\nAverage=%e\n\n",average); } else /* Slave */ { r=0; sum_slaves=0; for(i=0;i