+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1init36c1247

master
1.6 KiB46 linesraw
1// Author: Wes Kendall
2// Copyright 2011 www.mpitutorial.com
3// This code is provided freely with the tutorials on mpitutorial.com. Feel
4// free to modify it for your own use. Any distribution of the code must
5// either provide a link to www.mpitutorial.com or keep this header intact.
6//
7// Example using MPI_Send and MPI_Recv to pass a message around in a ring.
8//
9#include <mpi.h>
10#include <stdio.h>
11#include <stdlib.h>
12
13int main(int argc, char** argv) {
14  // Initialize the MPI environment
15  MPI_Init(NULL, NULL);
16  // Find out rank, size
17  int world_rank;
18  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
19  int world_size;
20  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
21
22  int token;
23  // Receive from the lower process and send to the higher process. Take care
24  // of the special case when you are the first process to prevent deadlock.
25  if (world_rank != 0) {
26    MPI_Recv(&token, 1, MPI_INT, world_rank - 1, 0, MPI_COMM_WORLD,
27             MPI_STATUS_IGNORE);
28    printf("Process %d received token %d from process %d\n", world_rank, token,
29           world_rank - 1);
30  } else {
31    // Set the token's value if you are process 0
32    token = -1;
33  }
34  MPI_Send(&token, 1, MPI_INT, (world_rank + 1) % world_size, 0,
35           MPI_COMM_WORLD);
36  // Now process 0 can receive from the last process. This makes sure that at
37  // least one MPI_Send is initialized before all MPI_Recvs (again, to prevent
38  // deadlock)
39  if (world_rank == 0) {
40    MPI_Recv(&token, 1, MPI_INT, world_size - 1, 0, MPI_COMM_WORLD,
41             MPI_STATUS_IGNORE);
42    printf("Process %d received token %d from process %d\n", world_rank, token,
43           world_size - 1);
44  }
45  MPI_Finalize();
46}