0

I am experimenting with MPI and so far I have this small program that computes a simple sum:

#include <mpi.h>
#include <stdio.h>

int main(int argc, char *argv[]){
int i=0, myid, nproc,N=5;
double result=0.0,res;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &nproc);

MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);

while (i<N) { 
    result += i;
    i++;

    printf("process %d i %d\n",myid,i);
    MPI_Reduce(&result, &res, 1, MPI_DOUBLE,MPI_SUM, 0, MPI_COMM_WORLD);
}
if (myid == 0)
{
    printf("result = %lf\n", res);
}
MPI_Finalize();

}

Based on the results from the print, I can see that i reaches the limit (5) for every process. How can I configure it to keep something like a global counter so that i reaches the limit only one time for all processes?

mnmbs
  • 353
  • 3
  • 13
  • 1
    Before diving into the excellent linked question/answer, I would strongly encourage you to familiarize yourself with the basic principles of MPI: independent processes and explicit communication via messages. Think if you can design your application around these principles, or ask if you are stuck. – Zulan May 18 '16 at 19:56
  • I am trying to calculate pi in a master-slave like way. The result i am getting is 4 times the expected result as i am using 4 processes and i think that the problem is that the task counter is increased by every process. – mnmbs May 18 '16 at 20:28
  • There are actually many examples on how to use MPI for computing pi out there. – Zulan May 18 '16 at 20:55
  • Yes but not using a master slave and i cannot figure out how to keep the master process out of the calculation and still get the correct result – mnmbs May 18 '16 at 20:57

1 Answers1

0

There is no automatically global counter with MPI. I think you will have to communicate the increments to the counter manually.

renefritze
  • 2,167
  • 14
  • 25