#include #include #include #include #include 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_Reduce(&my_lucky_number, &global_min, /*count*/ 1, MPI_INT, MPI_MIN, /*root*/ 0, MPI_COMM_WORLD); MPI_Reduce(&my_lucky_number, &global_sum, /*count*/ 1, MPI_INT, MPI_SUM, /*root*/ 0, MPI_COMM_WORLD); MPI_Reduce(&my_lucky_number, &global_max, /*count*/ 1, MPI_INT, MPI_MAX, /*root*/ 0, 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); std::cout << "Process " << my_rank << ": my lucky number is " << std::setw(2) << std::setfill('0') << my_lucky_number << std::endl; if ( my_rank == 0 ) { double average = static_cast(global_sum) / process_count; std::cout << "Process " << my_rank << ": all minimum: " << std::setw(2) << global_min << std::endl; std::cout << "Process " << my_rank << ": all average: " << std::fixed << std::setprecision(2) << average << std::endl; std::cout << "Process " << my_rank << ": all maximum: " << std::setw(2) << global_max << std::endl; } if ( my_rank < process_count - 1 ) MPI_Send(&ready, /*count*/ 1, MPI_CHAR, /*dest*/ my_rank + 1, /*tag*/ 0, MPI_COMM_WORLD); MPI_Finalize(); }