Skip to content
Advertisement

MPI program does nothing – running on linux

I’ve written this MPI C program on linux. The master is supposed to send tasks to the slaves and receive data from the slaves (and if there’re more tasks to give them to the finished slaves).

After all the tasks are completed, it’s supposed to print a solution.

It prints nothing and I can’t figure out why. It isn’t stuck, it just finishes after a second and doesn’t print anything.

P.S- I’ve tried debugging by placing a printf in different places in the code. The only place in the code that printed something was before the MPI_Recv in the master section, and it printed a few times (less than the number of processes).

Here’s the full code:

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

#define NUMS_TO_CHECK 2000
#define RANGE_MIN -5
#define RANGE_MAX 5

#define PI  3.1415
#define MAX_ITER 100000

double func(double x);

int main (int argc, char *argv[])
{
    int numProcs, procId;
    int errorCode= MPI_ERR_COMM;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
    MPI_Comm_rank(MPI_COMM_WORLD, &procId);
    MPI_Status status;
    int i;
    double recieve=0;
    int countPositives=0;
    double arr[NUMS_TO_CHECK];
    double difference= (RANGE_MAX - RANGE_MIN) / NUMS_TO_CHECK;
    int counter = NUMS_TO_CHECK-1; //from end to start...
    //Initiallizing the array.
    for(i=0; i<NUMS_TO_CHECK; i++){
        arr[i]=RANGE_MIN+i*difference;
    }
    //master
    if(procId==0){
        //Send tasks to all procs
        for(i=1; i<numProcs; i++){
            MPI_Send(&arr[counter], 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
            counter--;
        }
        do{
            MPI_Recv(&recieve, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
            if(recieve>0) 
            {
                countPositives++;
            }
            MPI_Send(&arr[counter], 1, MPI_DOUBLE, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
            counter--;

        }while(counter>0);

        printf("Number of positives: %d", countPositives);
        MPI_Finalize();

    }
    //slaves
    else{
        MPI_Recv(&recieve, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        recieve=func(recieve);
        MPI_Send(&recieve, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);


    }

}

double func(double x) 
{
    int i;
    double value = x;
    int limit = rand() % 3 + 1;

    for(i = 0;  i < limit * MAX_ITER;  i++)
        value = sin(exp(sin(exp(sin(exp(value))))) - PI / 2) - 0.5;

    return value;
}

Advertisement

Answer

I think your slaves need to read data in a while loop. They only do 1 receive and 1 send. Whereas the master starts at 2000. That may be by design, so I may be wrong.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement