Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix: forgot to properly update migration.tesh
[simgrid.git] / examples / smpi / ring_c.c
1 /*
2  * Copyright (c) 2004-2006 The Trustees of Indiana University and Indiana
3  *                         University Research and Technology
4  *                         Corporation.  All rights reserved.
5  * Copyright (c) 2006      Cisco Systems, Inc.  All rights reserved.
6  *
7  * Simple ring test program
8  */
9
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <mpi.h>
13
14 int main(int argc, char *argv[])
15 {
16   int rank, size, next, prev, message, tag = 201;
17
18   /* Start up MPI */
19
20   MPI_Init(&argc, &argv);
21   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
22   MPI_Comm_size(MPI_COMM_WORLD, &size);
23
24   /* Calculate the rank of the next process in the ring.  Use the
25      modulus operator so that the last process "wraps around" to
26      rank zero. */
27
28   next = (rank + 1) % size;
29   prev = (rank + size - 1) % size;
30
31   /* If we are the "master" process (i.e., MPI_COMM_WORLD rank 0),
32      put the number of times to go around the ring in the
33      message. */
34
35   if (0 == rank) {
36     message = 10;
37
38     printf("Process 0 sending %d to %d, tag %d (%d processes in ring)\n",
39            message, next, tag, size);
40     MPI_Send(&message, 1, MPI_INT, next, tag, MPI_COMM_WORLD);
41     printf("Process 0 sent to %d\n", next);
42   }
43
44   /* Pass the message around the ring.  The exit mechanism works as
45      follows: the message (a positive integer) is passed around the
46      ring.  Each time it passes rank 0, it is decremented.  When
47      each processes receives a message containing a 0 value, it
48      passes the message on to the next process and then quits.  By
49      passing the 0 message first, every process gets the 0 message
50      and can quit normally. */
51
52   sleep(3);
53
54   while (1) {
55     MPI_Recv(&message, 1, MPI_INT, prev, tag, MPI_COMM_WORLD,
56              MPI_STATUS_IGNORE);
57
58     if (0 == rank) {
59       --message;
60       printf("Process 0 decremented value: %d\n", message);
61     }
62
63     MPI_Send(&message, 1, MPI_INT, next, tag, MPI_COMM_WORLD);
64     if (0 == message) {
65       printf("Process %d exiting\n", rank);
66       break;
67     }
68   }
69
70   /* The last process does one extra send to process 0, which needs
71      to be received before the program can exit */
72
73   if (0 == rank) {
74     MPI_Recv(&message, 1, MPI_INT, prev, tag, MPI_COMM_WORLD,
75              MPI_STATUS_IGNORE);
76   }
77
78   /* All done */
79
80   MPI_Finalize();
81   return 0;
82 }