Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
092423bb7888dd19078343a075389fa8e61a326b
[simgrid.git] / examples / smpi / pingpong.c
1 /* A simple example pingpong pogram to test MPI_Send and MPI_Recv */
2
3
4
5 #include <stdio.h>
6 #include <mpi.h>
7
8 main(int argc, char *argv[])
9 {
10           const int tag1 = 42, tag2= 43;           /* Message tag */
11           int rank; 
12           int size; 
13           int msg=99;
14           int err;
15           int pivot;
16           MPI_Status status;
17
18           err = MPI_Init(&argc, &argv); /* Initialize MPI */
19           if (err != MPI_SUCCESS) {
20                     printf("MPI initialization failed!\n");
21                     exit(1);
22           }
23           err = MPI_Comm_size(MPI_COMM_WORLD, &size); /* Get nr of tasks */
24           err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);     /* Get id of this process */
25           if ( size < 2 ) {
26                     printf("run this program with exactly 2 processes (-np 2)\n");
27                     MPI_Finalize();         
28                     exit(0);
29           }
30         if (0 == rank) {
31                                 printf("\n    *** Ping-pong test (MPI_Send/MPI_Recv) ***\n\n");
32           }
33
34         /* start pingpong tests between several pairs */
35           for (pivot=0; pivot<size-1; pivot++) {
36
37                     if (pivot == rank) {           
38                                 printf("\n== pivot=%d : pingpong [%d] <--> [%d]\n",pivot,pivot,pivot+1);
39
40                                 int dst= rank + 1;
41                                 printf("[%d] About to send 1st message '%d' to process [%d] \n", rank,msg, dst);
42                                 err = MPI_Send(&msg, 1, MPI_INT, dst, tag1, MPI_COMM_WORLD);
43
44                                 err = MPI_Recv(&msg, 1, MPI_INT, dst, tag2, MPI_COMM_WORLD, &status);    /* Receive a message */
45                                 printf("[%d] Received relpy message '%d' from process [%d] \n", rank,msg, dst);
46
47                     }
48                     if ((pivot+1) == rank) {
49                                 int src= rank - 1;
50                                 err = MPI_Recv(&msg, 1, MPI_INT, src, tag1, MPI_COMM_WORLD, &status);    /* Receive a message */
51                                 printf("[%d] Received 1st message '%d' from process [%d] \n", rank,msg, src);
52                                 msg++;
53                                 printf("[%d] increment message's value to  '%d'\n", rank,msg);
54                                 printf("[%d] About to send back message '%d' to process [%d] \n", rank,msg, src);
55                                 err = MPI_Send(&msg, 1, MPI_INT, src, tag2, MPI_COMM_WORLD);
56                     }
57           }
58           err = MPI_Finalize();         /* Terminate MPI */
59           return 0;
60 }