/* File: mpi_print_list.c * Purpose: Driver for a function that converts a list of ints into * in a string before printing. * * Compile: mpicc -g -Wall -o mpi_print_list mpi_print_list.c * Run: mpiexec -n

./mpi_print_list * * Input: n, the number of elements in the local lists * Output: The list generated by each process */ #include #include #include #include /* Ints in the lists will be between 0 and RMAX */ const int RMAX = 100; const int STRING_MAX = 10000; void Print_list(int list[], int n, int my_rank); int main(void) { int my_rank, n, i; MPI_Comm comm; int* list; MPI_Init(NULL, NULL); comm = MPI_COMM_WORLD; MPI_Comm_rank(comm, &my_rank); if (my_rank == 0) { printf("How many ints in each list?\n"); scanf("%d", &n); } MPI_Bcast(&n, 1, MPI_INT, 0, comm); list = malloc(n*sizeof(int)); srandom(my_rank); for (i = 0; i < n; i++) list[i] = random() % RMAX; Print_list(list, n, my_rank); free(list); MPI_Finalize(); return 0; } /* main */ /*------------------------------------------------------------------- * Function: Print_list * Purpose: Convert a list of ints to a single string before * printing. This should make it less likely that the * output is interrupted by another process. This is * mainly intended for debugging purposes. * In args: list: the ints to be printed * n: the number of ints * my_rank: the usual MPI variable */ void Print_list(int list[], int n, int my_rank) { char string[STRING_MAX]; char* s_p; int i; sprintf(string, "Proc %d > ", my_rank); // Pointer arithmetic: make s_p point to the character strlen(string) // into string; i.e., make it point at the `\0' s_p = string + strlen(string); for (i = 0; i < n; i++) { sprintf(s_p, "%d ", list[i]); s_p = string + strlen(string); } printf("%s\n", string); fflush(stdout); } /* Print_list */