MPIHelloWorldSendAndReceive
From Parawiki
MPIHelloWorldSendAndReceive.c
//compilation: //$ mpicc -o program MPIHelloWorldSendAndReceive.c //$ mpirun -np number_of_processes program //If you want to use multiple processors you have to use lamboot before! //if the mpi.h cannot be found by the compiler, try to locate mpi.h: //open a terminal and: $ locate mpi.h //and then include by giving the whole path to mpi.h //in this example there are two distict send and receive operations //distinction is made by tags and status #include <stdio.h> #include <string.h> #include "mpi.h" int main(int argc, char* argv[]) { int rank, size; //process rank and number of processes int source, destination; //the sender and the receiver int tag_message = 0; //tag for send/receive int tag_rank = 1; //tag for send/receive MPI_Status status_message; //stores status for MPI_Recv statements MPI_Status status_rank; //stores status for MPI_Recv statements char message[20]; //display messages to send/receive MPI_Init(&argc, &argv); //MPI initialize MPI_Comm_size(MPI_COMM_WORLD, &size); //get the number of processes MPI_Comm_rank(MPI_COMM_WORLD, &rank); //get the process ranks //process0 is going to receive messages from other processes //each process writes "hello world" to a message and sends it to the receiver process //each process sends its rank //process0, displays the message and the corresponding rank number if (rank!=0) { destination = 0; //set the receiver process process0 strcpy(message, "Hello World!"); //send the message to process0, use tag_message MPI_Send(message, strlen(message)+1, MPI_CHAR, destination, tag_message, MPI_COMM_WORLD); //send the rank to process0, use tag_rank MPI_Send(&rank, 1, MPI_INT, destination, tag_rank, MPI_COMM_WORLD); } else for(source = 1; source < size; source++){ //process0 receives the message by using tag_message and status_message MPI_Recv(message, 100, MPI_CHAR, source, tag_message, MPI_COMM_WORLD, &status_message); //process0 receives the rank by using tag_rank and status_rank MPI_Recv(&rank, 1, MPI_INT, source, tag_rank, MPI_COMM_WORLD, &status_rank); printf("This \"%s\"", message); printf("is sent from process %d of %d to process %d\n", rank, size, destination); } MPI_Finalize(); //MPI finalize return 0; }