#include #include #include #include #include const char* compare(double num, double ref) { if ( num < ref ) return "less than"; if ( num > ref ) return "greater than"; return "equals to"; } int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); int my_rank = -1; int process_count = -1; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &process_count); char hostname[MPI_MAX_PROCESSOR_NAME]; int hostname_length = -1; MPI_Get_processor_name(hostname, &hostname_length); srand( my_rank + time(nullptr) + clock() ); int my_lucky_number = rand() % 100; int global_min = -1; int global_sum = -1; int global_max = -1; MPI_Allreduce(&my_lucky_number, &global_min, /*count*/ 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); MPI_Allreduce(&my_lucky_number, &global_sum, /*count*/ 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&my_lucky_number, &global_max, /*count*/ 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); char ready = 'Y'; if ( my_rank != 0 ) MPI_Recv(&ready, /*capacity*/ 1, MPI_CHAR, /*source*/ my_rank - 1, /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); double average = static_cast(global_sum) / process_count; std::cout << std::setfill('0') << std::fixed << std::setprecision(2); if ( my_lucky_number == global_min ) std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2) << my_lucky_number << ") is the minimum ("<< std::setw(2) << global_min << ")\n"; std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2) << my_lucky_number << ") is " << compare(my_lucky_number, average) << " the average (" << std::setw(2) << average << ")\n"; if ( my_lucky_number == global_max ) std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2) << my_lucky_number << ") is the maximum (" << std::setw(2) << global_max << ")\n"; if ( my_rank < process_count - 1 ) MPI_Send(&ready, /*count*/ 1, MPI_CHAR, /*dest*/ my_rank + 1, /*tag*/ 0, MPI_COMM_WORLD); MPI_Finalize(); }