Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6ddb6236809c34be4eb3c4cd5e37df8c730e4a60
[simgrid.git] / teshsuite / smpi / pt2pt-pingpong / pt2pt-pingpong.c
1 /* A simple example ping-pong program to test MPI_Send and MPI_Recv */
2
3 /* Copyright (c) 2009-2019. 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 static void test_opts(int* argc, char **argv[]){
13   int found = 0, ret;
14   while ((ret = getopt(*argc, *argv, "s")) >= 0)
15   {
16     switch (ret) {
17     case 's':
18       found = 1;
19       break;
20     }
21   }
22   if (found!=1){
23     printf("(smpi_)getopt failed ! \n");
24   }
25 }
26
27 int main(int argc, char *argv[])
28 {
29   const int tag1 = 42;
30   const int tag2 = 43; /* Message tag */
31   int size;
32   int rank;
33   int msg = 99;
34   MPI_Status status;
35
36   int err = MPI_Init(&argc, &argv); /* Initialize MPI */
37
38   /* test getopt function */
39   test_opts(&argc, &argv);
40
41   if (err != MPI_SUCCESS) {
42     printf("MPI initialization failed!\n");
43     exit(1);
44   }
45   MPI_Comm_size(MPI_COMM_WORLD, &size);   /* Get nr of tasks */
46   MPI_Comm_rank(MPI_COMM_WORLD, &rank);   /* Get id of this process */
47   if (size < 2) {
48     printf("run this program with exactly 2 processes (-np 2)\n");
49     MPI_Finalize();
50     exit(0);
51   }
52   if (0 == rank) {
53     printf("\n    *** Ping-pong test (MPI_Send/MPI_Recv) ***\n\n");
54   }
55
56   /* start ping-pong tests between several pairs */
57   for (int pivot = 0; pivot < size - 1; pivot++) {
58     if (pivot == rank) {
59       printf("\n== pivot=%d : pingpong [%d] <--> [%d]\n", pivot, pivot, pivot + 1);
60
61       int dst = rank + 1;
62       printf("[%d] About to send 1st message '%d' to process [%d]\n", rank, msg, dst);
63       MPI_Send(&msg, 1, MPI_INT, dst, tag1, MPI_COMM_WORLD);
64
65       MPI_Recv(&msg, 1, MPI_INT, dst, tag2, MPI_COMM_WORLD, &status);     /* Receive a message */
66       printf("[%d] Received reply message '%d' from process [%d]\n", rank, msg, dst);
67     }
68     if ((pivot + 1) == rank) {
69       int src = rank - 1;
70       MPI_Recv(&msg, 1, MPI_INT, src, tag1, MPI_COMM_WORLD, &status);     /* Receive a message */
71       printf("[%d] Received 1st message '%d' from process [%d]\n", rank, msg, src);
72       msg++;
73       printf("[%d] increment message's value to  '%d'\n", rank, msg);
74       printf("[%d] About to send back message '%d' to process [%d]\n", rank, msg, src);
75       MPI_Send(&msg, 1, MPI_INT, src, tag2, MPI_COMM_WORLD);
76     }
77   }
78   MPI_Finalize();
79   return 0;
80 }