Logo AND Algorithmique Numérique Distribuée

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