[英]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.