Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
do-nothing program that uses only MPI_Init and MPI_Finalize works now.
[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 main(int argc, char *argv[]) {
17   const int tag = 42;         /* Message tag */
18   int id, ntasks, source_id, dest_id, err, i;
19   MPI_Status status;
20   int msg[2];     /* Message array */
21   
22   err = MPI_Init(&argc, &argv); /* Initialize MPI */
23   if (err != MPI_SUCCESS) {
24     printf("MPI initialization failed!\n");
25     exit(1);
26   }
27   err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
28   err = MPI_Comm_rank(MPI_COMM_WORLD, &id); /* Get id of this process */
29   if (ntasks < 2) {
30     printf("You have to use at least 2 processors to run this program\n");
31     MPI_Finalize();      /* Quit if there is only one processor */
32     exit(0);
33   }
34   
35   if (id == 0) {    /* Process 0 (the receiver) does this */
36     for (i=1; i<ntasks; i++) {
37       err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, \
38          &status);          /* Receive a message */
39       source_id = status.MPI_SOURCE;  /* Get id of sender */
40       printf("Received message %d %d from process %d\n", msg[0], msg[1], \
41        source_id);
42     }
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) printf("Ready\n");
54   return 0;
55 }
56