簡體   English   中英

MPI:Printf語句未在合適的時間執行

[英]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: " 解決方案是顯式刷新printfscanf之間的標准輸出:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM