Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
memory cleanups
[simgrid.git] / examples / smpi / pingpong.c
1 /* A simple example pingpong pogram to test MPI_Send and MPI_Recv */
2
3 /* Copyright (c) 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include <stdio.h>
10 #include <mpi.h>
11
12 int main(int argc, char *argv[])
13 {
14   const int tag1 = 42, tag2 = 43;       /* Message tag */
15   int rank;
16   int size;
17   int msg = 99;
18   int err;
19   int pivot;
20   MPI_Status status;
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, &size);   /* Get nr of tasks */
28   err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);   /* Get id of this process */
29   if (size < 2) {
30     printf("run this program with exactly 2 processes (-np 2)\n");
31     MPI_Finalize();
32     exit(0);
33   }
34   if (0 == rank) {
35     printf("\n    *** Ping-pong test (MPI_Send/MPI_Recv) ***\n\n");
36   }
37
38   /* start pingpong tests between several pairs */
39   for (pivot = 0; pivot < size - 1; pivot++) {
40
41     if (pivot == rank) {
42       printf("\n== pivot=%d : pingpong [%d] <--> [%d]\n", pivot, pivot,
43              pivot + 1);
44
45       int dst = rank + 1;
46       printf("[%d] About to send 1st message '%d' to process [%d] \n",
47              rank, msg, dst);
48       err = MPI_Send(&msg, 1, MPI_INT, dst, tag1, MPI_COMM_WORLD);
49
50       err = MPI_Recv(&msg, 1, MPI_INT, dst, tag2, MPI_COMM_WORLD, &status);     /* Receive a message */
51       printf("[%d] Received relpy message '%d' from process [%d] \n", rank,
52              msg, dst);
53
54     }
55     if ((pivot + 1) == rank) {
56       int src = rank - 1;
57       err = MPI_Recv(&msg, 1, MPI_INT, src, tag1, MPI_COMM_WORLD, &status);     /* Receive a message */
58       printf("[%d] Received 1st message '%d' from process [%d] \n", rank,
59              msg, src);
60       msg++;
61       printf("[%d] increment message's value to  '%d'\n", rank, msg);
62       printf("[%d] About to send back message '%d' to process [%d] \n",
63              rank, msg, src);
64       err = MPI_Send(&msg, 1, MPI_INT, src, tag2, MPI_COMM_WORLD);
65     }
66   }
67   err = MPI_Finalize();         /* Terminate MPI */
68   return 0;
69 }