I have a very simple MPI program to test the behavior of MPI_Reduce. My objectives are simple:
~ Start by having each process create a random number (range 1-100)
Then run program with mpirun -np 5 <program_name_here>
- Have process 0, find the sum of all 5 numbers
- Have process 1, find the product of all 5 numbers
- Have process 2, find the max of all 5 numbers
- Have process 3, find the min of all 5 numbers
- Have process 4, find the bitwise and of all 5 numbers
And here's my program:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
int sum = 0;
int product = 0;
int max = 0;
int min = 0;
int bitwiseAnd = 0;
int main ( int argc, char **argv )
{
int my_id, num_procs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
int num;
srand(time(NULL) * my_id);
num = rand() % 100; //give num the random number
printf("Process #%i: Here is num: %i\n",my_id,num);
if(my_id == 0){
printf("Okay it entered 0\n");
MPI_Reduce(&num, &sum,1,MPI_INT,MPI_SUM, 0, MPI_COMM_WORLD);
}else if(my_id == 1){
printf("Okay it entered 1\n");
MPI_Reduce(&num, &product,1,MPI_INT,MPI_PROD, 0, MPI_COMM_WORLD);
}else if(my_id == 2){
printf("Okay it entered 2\n");
MPI_Reduce(&num, &max,1,MPI_INT,MPI_MAX, 0, MPI_COMM_WORLD);
}else if(my_id == 3){
printf("Okay it entered 3\n");
MPI_Reduce(&num, &min,1,MPI_INT,MPI_MIN, 0, MPI_COMM_WORLD);
}else if(my_id == 4){
printf("Okay it entered 4\n");
MPI_Reduce(&num, &bitwiseAnd,1,MPI_INT,MPI_BAND, 0, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
if(my_id == 0){
printf("I am process %i and the sum is %i\n",my_id,sum);
printf("I am process %i and the product is %i\n",my_id,product);
printf("I am process %i and the max is %i\n",my_id,max);
printf("I am process %i and the min is %i\n",my_id,min);
printf("I am process %i and the bitwiseAdd is %i\n",my_id,bitwiseAnd);
}
MPI_Finalize();
}
This produces output like this:
[blah@blah example]$ mpirun -np 5 all
Process #2: Here is num: 21
Okay it entered 2
Process #4: Here is num: 52
Okay it entered 4
Process #0: Here is num: 83
Okay it entered 0
Process #1: Here is num: 60
Okay it entered 1
Process #3: Here is num: 66
Okay it entered 3
I am process 0 and the sum is 282
I am process 0 and the product is 0
I am process 0 and the max is 0
I am process 0 and the min is 0
I am process 0 and the bitwiseAdd is 0
[blah@blah example]$
Why doesn't process 0 pick up the MPI_Reduce results from the other processes?