Cleaned up src/MPI2_message_passing/.
[parallel_computing.git] / src / MPI2_message_passing / ring.c
1 /************************************************************************
2  * This file has been written as a sample solution to an exercise in a
3  * course given at the Edinburgh Parallel Computing Centre. It is made
4  * freely available with the understanding that every copy of this file
5  * must include this header and that EPCC takes no responsibility for
6  * the use of the enclosed teaching material.
7  *
8  * Author:      Joel Malard
9  *
10  * Contact:     epcc-tec@epcc.ed.ac.uk
11  *
12  * Purpose:     A program to try out non-blocking point-to-point
13  *              communications.
14  *
15  * Contents:    C source code.
16  *
17  ************************************************************************/
18
19 #include <stdio.h>
20 #include <mpi.h>
21
22 #define TAG_RIGHT 123
23
24 int main (int argc, char *argv[])
25 {
26   int ierror, rank, size;
27   int right, left, count, i;
28   int message, sum;
29
30   MPI_Status  send_status;
31   MPI_Status  recv_status;
32   MPI_Request request;
33
34   MPI_Init(&argc, &argv);
35   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
36   MPI_Comm_size(MPI_COMM_WORLD, &size);
37
38   count = 1;                        /* only sending a single MPI_INT */
39   right = (rank + 1) % size;
40   left = (rank - 1 + size) % size;  /* the '+ size' ensures 'left >= 0'. */
41
42   sum = 0;
43   message = rank;
44
45   for (i=0; i < size; i++) {
46     /* Issend because? */
47     MPI_Issend(&message, count, MPI_INT, right, TAG_RIGHT,
48                MPI_COMM_WORLD, &request);
49
50     MPI_Recv(&message, count, MPI_INT, left, TAG_RIGHT,
51              MPI_COMM_WORLD, &recv_status);
52
53     /* Wait because? */
54     MPI_Wait(&request, &send_status);
55
56     sum += message;
57   }
58
59   printf ("PE%d:\tSum = %d\n", rank, sum);
60
61   MPI_Finalize();
62 }