User Tools

Site Tools


c:mpi:ring-algorithm

This is an old revision of the document!


MPI Ring Algorithm

In this algorithm, processes form a logical ring. Each process sends a message to the next process in the ring (the last process sends the message back to the first process). This is a typical example used to demonstrate MPI communication patterns.

mpi-ring-algorithm.c
#include <mpi.h>
#include <stdio.h>
 
int main(int argc, char** argv) {
    // Initialize the MPI environment
    MPI_Init(&argc, &argv);
 
    // Get the rank of the process
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
 
    // Get the total number of processes
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
 
    // Variable to hold the message
    int token;
 
    // Determine the rank of the next process in the ring
    int next_rank = (world_rank + 1) % world_size;
 
    // Determine the rank of the previous process in the ring
    int prev_rank = world_rank - 1;
    if (prev_rank < 0) {
        prev_rank = world_size - 1;
    }
 
    // The first process starts the ring
    if (world_rank == 0) {
        // Set the initial value of the token
        token = -1;
        MPI_Send(&token, 1, MPI_INT, next_rank, 0, MPI_COMM_WORLD);
        MPI_Recv(&token, 1, MPI_INT, prev_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("Process %d received token %d from process %d\n", world_rank, token, prev_rank);
    } else {
        // All other processes
        MPI_Recv(&token, 1, MPI_INT, prev_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("Process %d received token %d from process %d\n", world_rank, token, prev_rank);
        // Increment the token's value
        token += 1;
        MPI_Send(&token, 1, MPI_INT, next_rank, 0, MPI_COMM_WORLD);
    }
 
    // Finalize the MPI environment
    MPI_Finalize();
}
c/mpi/ring-algorithm.1705481611.txt.gz · Last modified: 2024/01/17 10:53 by odefta