Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Improve the INSTALL file: some people just don't read the FAQ...
[simgrid.git] / src / smpi / sample / 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   const int tag = 42;         /* Message tag */
19   int id, ntasks, source_id, dest_id, err, i;
20   MPI_Status status;
21   int msg[2];     /* Message array */
22   
23   err = MPI_Init(&argc, &argv); /* Initialize MPI */
24   if (err != MPI_SUCCESS) {
25     printf("MPI initialization failed!\n");
26     exit(1);
27   }
28   err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
29   err = MPI_Comm_rank(MPI_COMM_WORLD, &id); /* Get id of this process */
30   if (ntasks < 2) {
31     printf("You have to use at least 2 processors to run this program\n");
32     MPI_Finalize();      /* Quit if there is only one processor */
33     exit(0);
34   }
35   
36   if (id == 0) {    /* Process 0 (the receiver) does this */
37     for (i=1; i<ntasks; i++) {
38       err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, \
39          &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   }
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) printf("Ready\n");
55   return 0;
56 }
57