/* * nearly the simplest possible message-passing program: * * process 0 sends a message, and process 1 receives and prints it. */ #include #include #include /* MPI header file */ #define MYTAG 0 #define BUFFLEN 2 /* a short function to print a message, clean up, and exit */ void error_exit(char msg[]) { fprintf(stderr, "%s", msg); MPI_Finalize(); exit(EXIT_FAILURE); } /* main program */ int main(int argc, char *argv[]) { int nprocs; int myid; int buff[BUFFLEN]; int source; int dest; MPI_Status status; /* initialize for MPI */ if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { fprintf(stderr, "MPI initialization error\n"); return EXIT_FAILURE; } /* get number of processes */ MPI_Comm_size(MPI_COMM_WORLD, &nprocs); if (nprocs != 2) error_exit("number of processes must be 2\n"); /* get this process's number (ranges from 0 to nprocs - 1) */ MPI_Comm_rank(MPI_COMM_WORLD, &myid); if (myid == 0) { /* in process 0: send message to process 1 */ buff[0] = 10; buff[1] = 20; dest = 1; if (MPI_Send(buff, BUFFLEN, MPI_INT, dest, MYTAG, MPI_COMM_WORLD) != MPI_SUCCESS) error_exit("error sending message\n"); printf("process 0 sent %d %d\n", buff[0], buff[1]); } else { /* in process 1: receive message from process 0 and print */ source = 0; if (MPI_Recv(buff, BUFFLEN, MPI_INT, source, MYTAG, MPI_COMM_WORLD, &status) != MPI_SUCCESS) error_exit("error receiving message\n"); printf("process 1 received %d %d\n", buff[0], buff[1]); } /* clean up for MPI */ MPI_Finalize(); return EXIT_SUCCESS; }