Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Alltoallv
[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 <mpi.h>
16
17 main(int argc, char *argv[])
18 {
19   const int tag = 42;           /* Message tag */
20   int id, ntasks, source_id, dest_id, err, i;
21   MPI_Status status;
22   int msg[2];                   /* Message array */
23
24   err = MPI_Init(&argc, &argv); /* Initialize MPI */
25   if (err != MPI_SUCCESS) {
26     printf("MPI initialization failed!\n");
27     exit(1);
28   }
29   err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
30   err = MPI_Comm_rank(MPI_COMM_WORLD, &id);     /* Get id of this process */
31   if (ntasks < 2) {
32     printf("You have to use at least 2 processors to run this program\n");
33     MPI_Finalize();             /* Quit if there is only one processor */
34     exit(0);
35   }
36
37   if (id == 0) {                /* Process 0 (the receiver) does this */
38     for (i = 1; i < ntasks; i++) {
39       err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status);    /* Receive a message */
40       source_id = status.MPI_SOURCE;    /* Get id of sender */
41       printf("Received message %d %d from process %d\n", msg[0], msg[1],
42              source_id);
43     }
44   } else {                      /* Processes 1 to N-1 (the senders) do this */
45     msg[0] = id;                /* Put own identifier in the message */
46     msg[1] = ntasks;            /* and total number of processes */
47     dest_id = 0;                /* Destination address */
48     sleep(3);
49     err = MPI_Send(msg, 2, MPI_INT, dest_id, tag, MPI_COMM_WORLD);
50   }
51
52   err = MPI_Finalize();         /* Terminate MPI */
53   if (id == 0)
54     printf("Ready\n");
55   return 0;
56 }