/* compile: /usr/local/mpich-1.2.0/bin/mpicc par.ex5_24.skel.c run : nice /usr/local/mpich-1.2.0/bin/mpirun -np 10 a.out Difference to ex23: block sends. To understand the program, draw the processors and slowly draw each message. All statements after MPI_Init are executed by (-np) 10 processes, PIDs are 0..P-1. */ #include #include #include /* a variable needeed for call, result not used */ static MPI_Status tmpstat; /* logical directions */ #define Left (PID-1) #define Right (PID+1) #define Any MPI_ANY_SOURCE /* Send and Receive operations DEST & SOURCE can be Left/Right or a PID (int 0..P-1) SOURCE can be Any */ /* Send the value of an int _variable_ VAR to destination process DEST */ #define Send(DEST, VAR) MPI_Send(&VAR, 1, MPI_INT, DEST, 0, MPI_COMM_WORLD) /* Send the COUNT int:s starting from address ADDR to to destination process DEST */ #define BSend(DEST, ADDR, COUNT) MPI_Send(ADDR, COUNT, MPI_INT, DEST, 0, MPI_COMM_WORLD) /* Receive an integer to an int variable VAR from destination process SOURCE */ #define Receive(SOURCE, VAR) MPI_Recv(&VAR, 1, MPI_INT, SOURCE, 0, MPI_COMM_WORLD, &tmpstat) /* Receive a COUNT int:s to address starting ADDR from destination process SOURCE */ #define BReceive(SOURCE, ADDR, COUNT) MPI_Recv(ADDR, COUNT, MPI_INT, SOURCE, 0, MPI_COMM_WORLD, &tmpstat) int main(int argc, char **argv) { int PID, /* process-ID */ P; /* number of processes */ /* own variables */ int i, ok = 1; int *s_arr, *r_arr; /* keep these 3 calls */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &PID); MPI_Comm_size(MPI_COMM_WORLD, &P); /* actual code */ /* space allocation */ r_arr = (int*)malloc(P * sizeof(int)); s_arr = (int*)malloc(P * sizeof(int)); if (!r_arr || !s_arr) exit(1); if (PID == 0) { /* 1st processor sends block to all */ for (i = 0; i < P; i++) s_arr[i] = i; for (i = 1; i < P; i++) BSend(i, s_arr, P); } else { /* others receive from 1st */ BReceive(0, r_arr, P); for (i = 0; i < P; i++) { if (r_arr[i] != i) { printf("Pros: %d, i: %d r_arr_i %d \n", PID, i, r_arr[i]); ok = 0; } } printf("Pros: %d ok = %d\n", PID, ok); } free(s_arr); free(r_arr); /* keep this call */ MPI_Finalize(); exit(0); }