1 /* A first simple SPMD example program using MPI */
3 /* The program consists of on receiver process and N-1 sender */
4 /* processes. The sender processes send a message consisting */
5 /* of their process identifier (id) and the total number of */
6 /* processes (ntasks) to the receiver. The receiver process */
7 /* prints out the values it receives in the messeges from the */
10 /* Compile the program with 'mpicc first.c -o first' */
11 /* To run the program, using four of the computers specified in */
12 /* your hostfile, do 'mpirun -machinefile hostfile -np 4 first */
18 int main(int argc, char *argv[])
20 const int tag = 42; /* Message tag */
21 int id, ntasks, source_id, dest_id, err, i;
23 int msg[2]; /* Message array */
25 err = MPI_Init(&argc, &argv); /* Initialize MPI */
26 if (err != MPI_SUCCESS) {
27 printf("MPI initialization failed!\n");
30 err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
31 err = MPI_Comm_rank(MPI_COMM_WORLD, &id); /* Get id of this process */
33 printf("You have to use at least 2 processors to run this program\n");
34 MPI_Finalize(); /* Quit if there is only one processor */
38 if (id == 0) { /* Process 0 (the receiver) does this */
39 for (i = 1; i < ntasks; i++) {
40 err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status); /* Receive a message */
41 source_id = status.MPI_SOURCE; /* Get id of sender */
42 printf("Received message %d %d from process %d\n", msg[0], msg[1],
45 } else { /* Processes 1 to N-1 (the senders) do this */
46 msg[0] = id; /* Put own identifier in the message */
47 msg[1] = ntasks; /* and total number of processes */
48 dest_id = 0; /* Destination address */
50 err = MPI_Send(msg, 2, MPI_INT, dest_id, tag, MPI_COMM_WORLD);
53 err = MPI_Finalize(); /* Terminate MPI */