Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <stdlib.h>
  4. #include "mpi.h"
  5.  
  6. // a)
  7. // Returns the gcd of 2 numbers
  8. int gcd(int a, int b){
  9.     while(a != b)
  10.         if(a > b)
  11.       a -= b;
  12.     else
  13.       b -= a;
  14.      
  15.     return a;
  16. }
  17.  
  18. // b) Implement the addreduce pattern
  19. int main(int argc, char** argv) {
  20.  
  21.    int size, rank;
  22.    MPI_Status status;
  23.  
  24.    MPI_Init(&argc, &argv);
  25.  
  26.    MPI_Comm_size(MPI_COMM_WORLD, &size);
  27.    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  28.    
  29.    int shift = 1;
  30.    
  31.    // generate 2 random integers per process
  32.    srand(time(NULL));
  33.    int a = rank * 97 * rand(); // a always stays fix per process, will be the local result
  34.    int b = rank * 311 * rand(); // b will be received from other processes (except in the first round)
  35.  
  36.    int num_rounds = size; // change this value to set how many rounds the algorithms will be executed.
  37.                           // Standard value is: size
  38.    while(num_rounds > 0) {
  39.      int result = gcd(a, b);
  40.      
  41.      MPI_Status status;
  42.    printf("Process: %d sends to:%d and receives from:%d\n",rank,(rank + shift) % size,(rank - shift / 2) % size);
  43.      MPI_Sendrecv(&result, 1, MPI_INT, (rank + shift) % size    , 0,
  44.                   &b     , 1, MPI_INT, (rank - shift / 2) % size, 0, MPI_COMM_WORLD, &status);
  45.      a = result;
  46.      shift *= 2;
  47.      num_rounds--;
  48.    }
  49.    
  50.    // do sth with the results e.g. print it:
  51.    printf("Process %d result is: %d\n", rank, a);
  52.    
  53.    MPI_Finalize();
  54.  
  55.    return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement