0

What I have

I have a C-program using MPI, and it uses 4 processes: 1 vehicle(taskid=0) and 3 passengers. Vehicle can accommodate 2 passengers at a time. 3 customers keep coming back to get a ride.

For Vehicle, I have:

int passengers[C] = {0};
while(1)
    MPI_Recv(&pid, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status);
    //put pid in passengers[totalNumberArrived]
    if(totalNumberArrived == 2)    
        printf("vehicle left...");
        sleep(5);
        printf("vehicle came back...");
        for (i=0; i<2; i++)
            MPI_Send(&passengers[i], 1, MPI_INT, passengers[i], 1, MPI_COMM_WORLD);
        totalNumberArrived = 0;
    if(done)//omitting the details here
        break; 

And, for each passengers, I have:

for (i to NumOfRound)
    sleep(X);
    printf("%d is sending a msg", tasked)
    MPI_Send(&taskid, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
    MPI_Recv(&pid, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &pstatus);
    printf("%d received from %d\n", tasked, pid, pstatus.MPI_SOURCE);

issue

If the vehicle left for a ride with taskid 1 and 3, I expect to see this kind of output:

vehicle left...
vehicle came back...
1 is sending a msg 
3 is sending a msg (this could be before 1's msg though)

but I sometimes get

vehicle left...
1 is sending a msg
3 is sending a msg
vehicle came back...

which looks like the passenger is not blocked until the vehicle comes back.

I thought that MPI_Recv blocks the task until it gets a msg from the vehicle, so I researched and read that MPI_Recv does block but this kind of issues occur because the printf is not necessarily printing in order. I also read that some recommends to use flush but in some cases flush doesn't work.

I'm not sure what I should do in my case. Is it really just the matter of printf order?

I've also read this: Ordering Output in MPI

and wonder if I should add a master thread and let it be the central controller for vehicle and passengers??

Community
  • 1
  • 1
kabichan
  • 1,063
  • 4
  • 19
  • 49
  • Possible duplicate of [MPI - Printing in an order](https://stackoverflow.com/questions/17570996/mpi-printing-in-an-order) – Zulan May 11 '18 at 08:29

1 Answers1

1

You can't rely on printing output to be ordered between processes. The only thing you can count on is that output will be ordered per processes. Therefore, if for some reason it's critical that you can print things to STDOUT/STDERR in order, you need to aggregate it to one process first.

Wesley Bland
  • 8,816
  • 3
  • 44
  • 59