MPI Hello World
Jump to navigation
Jump to search
This is a simple example of workers sending a message to a master process using the Message Passing Interface, MPI. If you copy it into a file called main.c, you can compile it with "mpicc main.c -o hello".
#include <stdio.h>
#include <mpi.h>
int main(int argc, char ** argv)
{
int size,rank;
int length;
char name[80];
MPI_Status status;
int workerIdx;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Get_processor_name(name,&length);
if (rank==0) {
printf("Hello MPI from the server process!\n");
for (workerIdx=1; workerIdx<size; workerIdx++) {
MPI_Recv(name, 80, MPI_CHAR, workerIdx, 999, MPI_COMM_WORLD, &status);
printf("Hello MPI!\n");
printf(" message from %d of %d on %s\n", workerIdx, size, name);
}
} else {
MPI_Send(name,80,MPI_CHAR,0,999,MPI_COMM_WORLD);
}
MPI_Finalize();
}