Skip to content

Instantly share code, notes, and snippets.

@secondspass
Last active December 11, 2020 16:08
Show Gist options
  • Save secondspass/35caed61a2f999723f4e47ab2b874b77 to your computer and use it in GitHub Desktop.
Save secondspass/35caed61a2f999723f4e47ab2b874b77 to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int world_rank, world_size, token;
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
if (world_rank != 0) {
MPI_Recv(&token, 1, MPI_INT, world_rank - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printf("Process %d received token %d from process %d\n", world_rank, token, world_rank - 1);
} else {
token = -1;
}
MPI_Send(&token, 1, MPI_INT, (world_rank + 1) % world_size, 0, MPI_COMM_WORLD);
if (world_rank == 0) {
MPI_Recv(&token, 1, MPI_INT, world_size - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printf("Process %d received token %d from process %d\n", world_rank, token, world_size - 1);
}
MPI_Finalize();
}
/*
For 4 processes, output would look something like:
Process 0 received token -1 from process 3
Process 3 received token -1 from process 2
Process 1 received token -1 from process 0
Process 2 received token -1 from process 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment