Philip
Philip

Reputation: 137

Sum vector of integer using MPI c

I want to sum vector of integer using MPI.

Let's assume I have a vector a with 20 elements and a vector b with 20 elements too and I want to sum them in a vector c.

The rank 0 will send parts of the vector a and b to another rank,that will calculate the sum and then return another vector with the answer to rank 0. and so on.

The point is, the values that are passed between the ranks (process) is not working. Should I use pointer? What should I do.?

#include <iostream>
#include <stdio.h>
#include <stdlib.h> 
#include "mpi.h"

using namespace std;

int main(int argc, char *argv[])
{
  int num; 
  int mpi_myrank, mpi_size, mpi_tag, mpi_from = 0;
  MPI::Status mpi_status;

  MPI::Init(argc, argv);
  mpi_myrank = MPI::COMM_WORLD.Get_rank();
  mpi_size = MPI::COMM_WORLD.Get_size();


     int a[20];
     int b[20];
     int c[20];
     int delta = 5; // seria n / size = 5
     int size=4;
     int *buffer; 
     buffer = (int*) malloc(delta*sizeof(int)); 
     for(int i = 0 ; i<20;i++){
        a[i] = i;
        b[i] = i;
    }




  if (mpi_myrank == 0) {
    mpi_tag = 100;
    for(int i=1 ; i<size ; i++){

        for(int j=0 ; j<delta ; j++){   
            buffer[j] = a[(delta*i) +j];    
            MPI::COMM_WORLD.Send(&buffer,delta, MPI::INT, i, mpi_tag); 
        }
        for(int j=0 ; j<delta ; j++){   
            buffer[j] = b[(delta*i) +j];
             MPI::COMM_WORLD.Send(&buffer,delta, MPI::INT, i, mpi_tag); 
        }

    }

    for(int j=0; j<delta;j++ ){
        c[j] = a[j] + b[j];
    }

    for(int i=1; i<size;i++) {
        MPI::COMM_WORLD.Recv(&buffer, delta, MPI::INT, i, mpi_tag, mpi_status); 
        for(int j=0 ; j<delta;j++){
            c[(delta*i) + j] = buffer[j];       
        }
    }

    for(int i=0 ; i<20 ; i++){
        cout << "posicao " << i << " igual a " << c[i] << endl;
    }


}

  else {
    mpi_tag = 100;
    //int *bufa; 
    //bufa = (int*) malloc(delta*sizeof(int)); 
    //int *bufb; 
    //bufb = (int*) malloc(delta*sizeof(int));

    int bufa[delta];
    int bufb[delta];
    int resp[delta];
    MPI::COMM_WORLD.Recv(&bufa, delta, MPI::INT, 0, mpi_tag, mpi_status);   
    MPI::COMM_WORLD.Recv(&bufb, delta, MPI::INT, 0, mpi_tag, mpi_status);

    for(int i=0; i<delta ;i++){
        resp[delta] = bufa[i] + bufb[i]; 
    }   

    MPI::COMM_WORLD.Send(&resp,delta, MPI::INT, 0, mpi_tag);

  } // fim else

  MPI::Finalize();
  return 0;
} // fim main

Upvotes: 0

Views: 2951

Answers (1)

kraffenetti
kraffenetti

Reputation: 365

This part of your code looks incorrect

for(int i=0; i<delta ;i++){
    resp[delta] = bufa[i] + bufb[i]; 
}

You are overwriting the same position of the array in a loop, meaning the other positions may have garbage values.

Upvotes: 1

Related Questions