/* tags.c SJ An example of using tags to restrict messages */ #include #include #include #include #define MAXP 32 #define MESSAGES 4 /* a variable needeed for call, result not used */ static MPI_Status tmpstat; int main(int argc, char **argv) { int PID, /* process-ID */ P; /* number of processes */ /* own variables */ int v1, i, m; /* keep these 3 calls */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &PID); MPI_Comm_size(MPI_COMM_WORLD, &P); /* actual code */ if (PID == 0) { /* process 0 is the master */ int p; MPI_Status stat; printf("0: receive from any process messages with tag %d\n", MESSAGES); for (p = 1; p < P; p++) { MPI_Recv(&v1, 1, MPI_INT, MPI_ANY_SOURCE, MESSAGES, MPI_COMM_WORLD, &stat); printf("0: process %d returned %d with tag %d\n", stat.MPI_SOURCE, v1, stat.MPI_TAG); } printf("0: receive from process 1 messages with any tag\n"); for (m = 0; m < MESSAGES-1; m++) { MPI_Recv(&v1, 1, MPI_INT, 1, MPI_ANY_TAG, MPI_COMM_WORLD, &stat); printf("0: process %d returned %d with tag %d\n", stat.MPI_SOURCE, v1, stat.MPI_TAG); } printf("0: receive rest\n"); for (m = 0; m < (MESSAGES-1)*(P-2); m++) { MPI_Recv(&v1, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &stat); printf("0: process %d returned %d with tag %d\n", stat.MPI_SOURCE, v1, stat.MPI_TAG); } } else { /* all other processes */ /* an array to control progress of send requests */ MPI_Request req[MESSAGES+1]; /* an array of statuses */ MPI_Status stats[MESSAGES+1]; /* array of messages to send */ int rnd[MESSAGES+1]; srand(PID); /* send MESSAGES msgs to 0 */ for (m = 1; m <= MESSAGES; m++) { sleep(rand()%3); rnd[m] = rand() % 10; MPI_Isend(rnd+m, 1, MPI_INT, 0, m, MPI_COMM_WORLD, req+m); } /* wait until all sent */ MPI_Waitall(MESSAGES, req+1, stats+1); sleep(2); printf("%d: sent:", PID); for (m = 1; m <= MESSAGES; m++) { printf(" %d", rnd[m]); } printf("\n"); } /* keep this call */ MPI_Finalize(); exit(0); }