Reputation: 1192
I' m trying to have each process calculate a sum and then send the sums back to the root process.
However, the printf("\nSUMS[%d] = %d",i,sums[i]);
line prints out different sums than those printed at printf("\nI am process %d and my sum is %d", my_rank, sum);
Only the sum of root is the same with sums[0]
.
Can someone explain why this happens? Excuse me if this question has an obvious answer but I'm new to MPI.
sum = 0;
for ( i=0 ; i < np; i++)
sum += y[i];
printf("\nI am process %d and my sum is %d", my_rank, sum);
if (!my_rank)
sums = (int *)malloc(sizeof(int) * comm_size);
MPI_Gather(&sum, 1, MPI_INT, sums, comm_size, MPI_INT, 0, MPI_COMM_WORLD);
if (!my_rank)
for ( i = 0; i < comm_size; i++)
printf("\nSUMS[%d] = %d",i,sums[i]);
Upvotes: 0
Views: 1683
Reputation: 9817
According to the documentation of mpich on MPI_Gather()
the fifth argument of this function recvcount
is the number of elements for any single receive. In the code you posted, comm_size
is used, but it is the total number of elements to be received. Hence, the following line could solve your problem:
MPI_Gather(&sum, 1, MPI_INT, sums, 1, MPI_INT, 0, MPI_COMM_WORLD);
If it does not work, please let us know!
Upvotes: 1