Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e34a2122bc8cc1fe4d9f4e06006ae9007972362d
[simgrid.git] / examples / smpi / second.c
1 /* A first simple SPMD example program using MPI                  */
2
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     */
8 /* senders.                                                       */
9
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    */
13
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <mpi.h>
17
18 int main(int argc, char *argv[])
19 {
20   const int tag = 42;           /* Message tag */
21   int id, ntasks, source_id, dest_id, err, i;
22   MPI_Status status;
23   int msg[2];                   /* Message array */
24
25   err = MPI_Init(&argc, &argv); /* Initialize MPI */
26   if (err != MPI_SUCCESS) {
27     printf("MPI initialization failed!\n");
28     exit(1);
29   }
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 */
32   if (ntasks < 2) {
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 */
35     exit(0);
36   }
37
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],
43              source_id);
44     }
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 */
49     sleep(3);
50     err = MPI_Send(msg, 2, MPI_INT, dest_id, tag, MPI_COMM_WORLD);
51   }
52
53   err = MPI_Finalize();         /* Terminate MPI */
54   if (id == 0)
55     printf("Ready\n");
56   return 0;
57 }