Logo AND Algorithmique Numérique Distribuée

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