Search code examples
cmpi

Continuous sending/receiving messages in a loop


I am trying write a program, where the process 0 should start the initialization of sending messages to a random process other than itself, then the random process selected should receive the message and send to another random process.

This should happen until the requested number of messages to be sent is done, which is given by the user as input.

I see that my program is either sending messages at the max 2, or else, even none, and giving me the following error:

ONE OF THE PROCESSES TERMINATED BADLY: CLEANING UP APPLICATION TERMINATED WITH THE EXIT STRING: Terminated (signal 15)

The random generation part is not included, which is working fine:

if(rank==0)
{
    rnum=rgenerator(rank,size);
    string++;
    MPI_Send(&string, 50, MPI_INT, rnum, rnum, MPI_COMM_WORLD);
    printf("\n process %d sends message to process %d",rank, rnum);
    
    //MPI_Recv(&flag, 100, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
    
}
    
while(flag!=1)
{
    if(MPI_Recv(&string, 50, MPI_INT, MPI_ANY_SOURCE, rank, MPI_COMM_WORLD, &status)==MPI_SUCCESS)
    {   
        printf("\n process %d receives message from process %d count : %d",rank, status.MPI_SOURCE, string);
        rnum=rgenerator(rank,size);
        printf("\n Random num generated is %d",rnum);
        string=string+1;
        MPI_Send(&string, 50, MPI_INT, rnum, rnum, MPI_COMM_WORLD);
        count++;
        
        printf("\n process %d sends message to process %d", rank, rnum);

        //MPI_Bcast(&count, 40, MPI_INT, rank, MPI_COMM_WORLD);
        if(string==n)
        {
            printf("\n\n Messages reached");
            flag=1;
        }
    }
    else 
        flag=0;
    }

Solution

  • You should make sure that you have the same number of send and receive operations.

    In your code, you have one send operation more than you have receive operations. Therefore, one process will crash.

    To avoid this, you need to send only if your flag is not equal to 1:

    //MPI_Send(&string, 50, MPI_INT, rnum, rnum, MPI_COMM_WORLD);
    count++;
    
    printf("\n process %d sends message to process %d", rank, rnum);
    
    //MPI_Bcast(&count, 40, MPI_INT, rank, MPI_COMM_WORLD);
    if(string==n)
    {
       printf("\n\n Messages reached");
       flag=1;
    }
    
    if(flag!=1)
    {//make sure that you need to send one message.
        MPI_Send(&string, 50, MPI_INT, rnum, rnum, MPI_COMM_WORLD);
    }