Niteya Shah
Niteya Shah

Reputation: 1824

MPI sum of array receive working for only one rank

I am trying to find the sum of an array of length 100 elements using MPI, under the restrictions of only using MPI_Send and MPI_receive , the code that I have written finds the sum of each processor but during the re-send to the main processor(rank=0) my code only receives from one processor

My Code

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include "mpi.h"
#include "math.h"

int val = 1;
int main(int argc, char* argv[]) {

    int my_rank;
    int p;
    int ierr;
    int i;
    int a[100];
    int q=0;
    for (i = 0; i <100; i++)
    {
        a[i] = i+1;
    }
    int send,recv;
    MPI_Status status;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    int part = 100 /(p-1);
    if (my_rank == 0)
    {
        for (i = 1; i < p; i++)
        {
            send = part * (i-1);
            MPI_Send(&send, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
        }

    }
    else
    {
        MPI_Recv(&recv, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
        for (i = recv; i < recv + part; i++)
        {
            val = val+a[i];

        }
        printf("%d\n", val);
        MPI_Send(&val, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
    }
    if (my_rank == 0)
    {
        MPI_Recv(&val, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
        printf("%d", val);
        q = q + val;

    }
    MPI_Finalize();
    if (my_rank == 0)
    {
        printf("The output is %d\n", q);
    }
    return 0;
}

My output enter image description here

where am i going wrong

Upvotes: 0

Views: 807

Answers (1)

Mat&#250;š Bako
Mat&#250;š Bako

Reputation: 398

Because you only recieve the result from one process. To recieve all results, iterate over process ranks:

if (my_rank == 0)
{
    for (rank = 1; rank < proc_cnt; rank++)
    {
        MPI_Recv(&val, 1, MPI_INT, rank, 0, MPI_COMM_WORLD, &status);
        printf("value of rank %d is %d", rank, val);
        q = q + val;
    }

}

Ordinarily, this a bad practice and may lead to deadlocks. Use mpi_gather() if allowed.

Upvotes: 5

Related Questions