+/EE360P

distributed systems

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

vijaygarg1init36c1247

master
1.7 KiB49 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// Ping pong example with MPI_Send and MPI_Recv. Two processes ping pong a
8// number back and forth, incrementing it until it reaches a given value.
9//
10#include <mpi.h>
11#include <stdio.h>
12#include <stdlib.h>
13
14int main(int argc, char** argv) {
15  const int PING_PONG_LIMIT = 10;
16
17  // Initialize the MPI environment
18  MPI_Init(NULL, NULL);
19  // Find out rank, size
20  int world_rank;
21  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
22  int world_size;
23  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
24  printf("rank = %d size = %d \n", world_rank, world_size);
25
26  // We are assuming at least 2 processes for this task
27  if (world_size != 2) {
28    fprintf(stderr, "World size must be two for %s\n", argv[0]);
29    MPI_Abort(MPI_COMM_WORLD, 1);
30  }
31
32  int ping_pong_count = 0;
33  int partner_rank = (world_rank + 1) % 2;
34  while (ping_pong_count < PING_PONG_LIMIT) {
35    if (world_rank == ping_pong_count % 2) {
36      // Increment the ping pong count before you send it
37      ping_pong_count++;
38      MPI_Send(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD);
39      printf("%d sent and incremented ping_pong_count %d to %d\n",
40             world_rank, ping_pong_count, partner_rank);
41    } else {
42      MPI_Recv(&ping_pong_count, 1, MPI_INT, partner_rank, 0, MPI_COMM_WORLD,
43               MPI_STATUS_IGNORE);
44      printf("%d received ping_pong_count %d from %d\n",
45             world_rank, ping_pong_count, partner_rank);
46    }
47  }
48  MPI_Finalize();
49}