// // nearly the simplest possible message-passing program: // // process 0 sends a message, and process 1 receives and prints it. // #include #include // has exit(), etc. #include // MPI header file // a short function to print a message, clean up, and exit void errorExit(const char msg[]) { cerr << msg; MPI_Finalize(); exit(EXIT_FAILURE); } // main program int main(int argc, char *argv[]) { // initialize for MPI (should come before any other calls to // MPI routines) if (MPI_Init(&argc, &argv) != MPI_SUCCESS) errorExit("MPI initialization error\n"); // get number of processes int nprocs; MPI_Comm_size(MPI_COMM_WORLD, &nprocs); if (nprocs != 2) errorExit("number of processes must be 2\n"); // get this process's number (ranges from 0 to nprocs - 1) int myid; MPI_Comm_rank(MPI_COMM_WORLD, &myid); const int bufflen = 2; int buff[bufflen]; int mytag = 0; if (myid == 0) { // in process 0: send message to process 1 buff[0] = 10; buff[1] = 20; int dest = 1; if (MPI_Send(buff, bufflen, MPI_INT, dest, mytag, MPI_COMM_WORLD) != MPI_SUCCESS) errorExit("error sending message\n"); cout << "process 0 sent " << buff[0] << " " << buff[1] << endl; } else { // in process 1: receive message from process 0 and print MPI_Status status; int source = 0; if (MPI_Recv(buff, bufflen, MPI_INT, source, mytag, MPI_COMM_WORLD, &status) != MPI_SUCCESS) errorExit("error receiving message\n"); cout << "process 1 received " << buff[0] << " " << buff[1] << endl; } // clean up for MPI MPI_Finalize(); return EXIT_SUCCESS; }