/* gather.c - Let's look at the MPI gather function. * This multi-process program will have each node create some * random numbers. Then, the master node will gather all of these * sub-lists into a big list. The value of SIZE is how many * numbers each node will create. */ #define SIZE 100 #include #include #include #include int main() { int my_rank, num_processes, namelen, i; int local_list[SIZE], *global_list; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(NULL, NULL); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &num_processes); MPI_Get_processor_name(processor_name, &namelen); fprintf(stderr, "Process %d on %s\n", my_rank, processor_name); // Make sure each node has a different random number seed. srand(time(NULL) * (my_rank + 1)); // Let's create the local lists of random numbers. for (i = 0; i < SIZE; ++i) { local_list[i] = rand() % SIZE; printf("Process %d, local_list[ %d ] = %d\n", my_rank, i, local_list[i]); } /* Notice that the global_list was declared to be just a pointer. * This is because at compile time we don't know the size. * We use malloc to create the array once we know how many * processors there are. Each local_list of random numbers will * have SIZE numbers, so the global_list will have SIZE * num_processes. * Only the master node needs to allocate this space. */ if (my_rank == 0) { global_list = (int *) malloc (sizeof(int) * SIZE * num_processes); } MPI_Gather(local_list, SIZE, MPI_INT, global_list, SIZE, MPI_INT, 0, MPI_COMM_WORLD); // Print out the entire list if (my_rank == 0) { for (i = 0; i < SIZE * num_processes; ++i) printf("global_list[ %d ] = %d\n", i, global_list[i]); } MPI_Finalize(); return 0; }