This MPI program illustrates the use of MPI_Send and MPI_Recv functions. Basically, the master sends a message, “Hello, world”, to the process whose rank is 1, and then after having received the message, the process prints the message along with its rank.
Compile it using
Execute it using
MPI Hello World - 1
MPI Pi Calculation Lecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "mpi.h" | |
#define FROM_MASTER 1 | |
int main(int argc, char *argv[]) | |
{ | |
int rank, nprocs; | |
char message[12] = "Hello, world"; | |
/* status for MPI_Recv */ | |
MPI_Status status; | |
/* Initialize MPI execution environment */ | |
MPI_Init(&argc, &argv); | |
/* Determines the size of MPI_COMM_WORLD */ | |
MPI_Comm_size(MPI_COMM_WORLD, &nprocs); | |
/* Give each process a unique rank */ | |
MPI_Comm_rank(MPI_COMM_WORLD, &rank); | |
/* If the process is the master */ | |
if ( rank == 0 ) | |
/* Send message to process whose rank is 1 in the MPI_COMM_WORLD */ | |
MPI_Send(&message, 12, MPI_CHAR, 1, FROM_MASTER, MPI_COMM_WORLD); | |
/* If the process has rank of 1 */ | |
else if ( rank == 1 ) | |
{ | |
/* Receive message sent from master */ | |
MPI_Recv(&message, 12, MPI_CHAR, 0, FROM_MASTER, MPI_COMM_WORLD, &status); | |
/* Print the rank and message */ | |
printf("Process %d says : %s\n", rank, message); | |
} | |
/* Terminate MPI execution environment */ | |
MPI_Finalize(); | |
} |
Compile it using
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mpicc hello_send_recv.c |
Execute it using
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mpirun -np 2 ./a.out |
MPI Hello World - 1
MPI Pi Calculation Lecture