/* grader.c - Let's experiment with creating our own data type. */ #include #include #include #include #define SIZE 12 struct grade { int number; char letter; }; // I'm passing my rank so I can print out who is doing what. void assign_letter(struct grade student[], int num_students, int my_rank) { int i, percent; char letter; for (i = 0; i < num_students; ++i) { percent = student[i].number; if (percent >= 90) letter = 'A'; else if (percent >= 80) letter = 'B'; else if (percent >= 70) letter = 'C'; else if (percent >= 60) letter = 'D'; else letter = 'F'; student[i].letter = letter; printf("Process %d determines that %d is a %c.\n", my_rank, percent, letter); } } int main() { struct grade class[SIZE], *local_list; MPI_Datatype new_type; int my_rank, num_processes, i, local_size, name_length; int block_length[] = {1, 1}; int displacement[] = {0, 4}; int type[] = {MPI_INT, MPI_CHAR}; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &num_processes); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Get_processor_name(processor_name, &name_length); MPI_Type_create_struct(2, block_length, displacement, type, &new_type); MPI_Type_commit(&new_type); // Let's have the main node set the numerical grades randomly. if (my_rank == 0) { srand (time (NULL)); for (i = 0; i < SIZE; ++i) class[i].number = 50 + rand() % 50; } // Let's share the work of determining letter grades. // See p. 111 for format of scatter function. local_size = SIZE / num_processes; local_list = (struct grade *) malloc (sizeof(struct grade) * local_size); MPI_Scatter(class, local_size, new_type, local_list, local_size, new_type, 0, MPI_COMM_WORLD); assign_letter(local_list, local_size, my_rank); MPI_Gather(local_list, local_size, new_type, class, local_size, new_type, 0, MPI_COMM_WORLD); // Output if (my_rank == 0) for (i = 0; i < SIZE; ++i) printf("%2d %c\n", class[i].number, class[i].letter); MPI_Type_free(&new_type); MPI_Finalize(); return 0; } /* Output: Process 0 determines that 75 is a C. Process 2 determines that 72 is a C. Process 2 determines that 93 is a A. Process 2 determines that 72 is a C. Process 0 determines that 58 is a F. Process 2 determines that 92 is a A. Process 1 determines that 77 is a C. Process 0 determines that 93 is a A. Process 0 determines that 90 is a A. Process 1 determines that 58 is a F. Process 1 determines that 94 is a A. Process 1 determines that 86 is a B. 75 C 58 F 93 A 90 A 77 C 58 F 94 A 86 B 72 C 93 A 72 C 92 A */