Logo AND Algorithmique Numérique Distribuée

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