[英]MPI: Printf Statement is not executed at the right time
我有一个小程序。
#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;
}
输出是:
[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
在此输出中,您可以注意到这一点
输入缓冲区大小:
在输入缓冲区大小后打印/提示。
谁能告诉我如何解决这个问题。
我怀疑你的标准输出是行缓冲的。 在打印"process[%d]: buffer size : %d\\n"
(包含换行符)之前,不会打印"Enter the buffer size: "
。 解决方案是显式刷新printf
和scanf
之间的标准输出:
printf("Enter the buffer size: ");
fflush(stdout);
scanf("%d", &buf);
如果您使用Eclipse进行并行编程 ,那么(很可能)就是导致问题的原因。
这是PTP中的一些故障。 您也可以使用printf
来体验它,它只在您的程序执行完毕或关闭后打印(而不是在程序运行时)。
然后尝试从命令行运行代码,它将工作。
否则 ( 如果它仍然被绞死或给出奇怪的行为 ) 然后尝试呼叫
fflush(stdout)
或while ((c = getchar()) != '\\n' && c != EOF);
在阅读用户输入之前刷新所有内容。
你可以用它:
puts("Enter the buffer size:");
gets(buf);
那就是你拥有的。
printf("Buffer size is less than 10\n");
printf("Enter the buffer size: ");
我的意思是你怀疑它做什么? 看看之后: if(rank==0)
看看我的意思。 事实上,你甚至不使用你使用的%d 10。
你可能想要:
if(rank == 0) {
printf("Enter the buffer size: ");
scanf("%d", &buf);
printf("Buffer size is less than %d\n", buf);
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.