MPI: Printf Statement is not executed at the right time
Asked Answered
S

4

5

I have a small program.

#include "mpi.h"
#include <stdio.h>

int main(int argc, char *argv[])
{
int rank, size;
int buf;
int err;
MPI_Status status;

err = MPI_Init(&argc, &argv);
if(err == MPI_SUCCESS) {
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

if(rank == 0) {
printf("Buffer size is less than 10\n");
printf("Enter the buffer size: ");
scanf("%d", &buf);
MPI_Send(&buf, 1, MPI_INT, 1, 10,
MPI_COMM_WORLD);
}
else {
MPI_Recv(&buf, 1, MPI_INT, 0, 10,
MPI_COMM_WORLD, &status);
}
printf("process[%d]: buffer size : %d\n", rank,buf);

}
err = MPI_Finalize();
return 0;
}

The output is:

[veda@home-pc hpc]$ mpicc test.c
[veda@home-pc hpc]$ mpiexec -np 2 a.out
Buffer size is less than 10
3
Enter the buffer size: process[0]: buffer size : 3
process[1]: buffer size : 3

In this output, you can notice that

Enter the buffer size:

is printing/prompting after I entered the size of the buffer.

Can anyone tell me how to solve this problem.

Sunglass answered 11/10, 2010 at 0:25 Comment(0)
C
14

I suspect your standard output is line-buffered. The "Enter the buffer size: " is not printed until "process[%d]: buffer size : %d\n" (containing a newline) is printed. The solution is to explicitly flush the standard output between the printf and the scanf:

printf("Enter the buffer size: ");
fflush(stdout);
scanf("%d", &buf);
Coleoptile answered 11/10, 2010 at 5:57 Comment(1)
This page warns against doing that, saying that any input after printf() but before fflush() gets discarded.Guam
P
1

You can use it:

puts("Enter the buffer size:");
gets(buf);
Philbo answered 24/3, 2012 at 22:36 Comment(0)
C
1

If you are using Eclipse for parallel programming, then (most probably) that is what causes the issue.
It is some kind of glitch in PTP. You can also experience this with printf, it only prints after your program has finished execution or was shut down (not while the program is running).
Then try running your code from the command line, it will work.

Else (If it still gets hanged or gives weird behaviour) then try calling
fflush(stdout) or while ((c = getchar()) != '\n' && c != EOF);
to flush everything before reading user input.

Chivalrous answered 6/12, 2015 at 5:54 Comment(0)
F
-1

Well thats what you have.

printf("Buffer size is less than 10\n");
printf("Enter the buffer size: ");

I mean what do you suspect for it to do? Look right after: if(rank==0) to see what I mean. In fact, you don't even use the %d you use 10.

You probably want:

if(rank == 0) {
   printf("Enter the buffer size: ");
   scanf("%d", &buf);
   printf("Buffer size is less than %d\n", buf);
   //...
Feral answered 11/10, 2010 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.