/* 04_ring.c - pass values around a ring with non-blocking calls and sum them up.
 * Every rank sends to its right neighbour and receives from its left one, size-1 times,
 * so in the end each rank has seen every value. Works for any number of processes.
 * Build: mpicc -O2 -o 04_ring 04_ring.c
 * Run:   mpirun -np 5 ./04_ring
 */
#include <stdio.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    int right = (rank + 1) % size;
    int left  = (rank - 1 + size) % size;

    int passing = rank * rank;   /* the value this rank contributes */
    int sum = passing;
    int incoming;

    for (int step = 1; step < size; step++) {
        MPI_Request req[2];
        MPI_Irecv(&incoming, 1, MPI_INT, left,  0, MPI_COMM_WORLD, &req[0]);
        MPI_Isend(&passing,  1, MPI_INT, right, 0, MPI_COMM_WORLD, &req[1]);
        MPI_Waitall(2, req, MPI_STATUSES_IGNORE);   /* only now may we touch the buffers */
        sum += incoming;
        passing = incoming;                         /* forward what we just received */
    }

    printf("rank %d: sum of rank^2 over all ranks = %d\n", rank, sum);
    MPI_Finalize();
    return 0;
}
