虽然 运行 我的代码在 MPI 中,但尽管遵循了正确的语法,但根进程永远不会执行

While running my code in MPI, the root process never executes despite following the correct syntax

在尝试使用 MPI 库执行用 C 编写的代码时,我遇到了一些非常奇怪的事情。 当我尝试

时,我的代码还没有产生语法错误
 mpirun -n 3 ./q4

我明白了

hello
hello
hello
from the other side.
from the other side.
from the other side.

好像从来没有进入过0级进程。我不知道为什么会这样。此代码在结构上与我编写的其他一些示例相同(如果需要,我可以提供完整代码) 但是,如果我在第六行之后输入任意两个随机的东西,我会得到这个

1213
123
Enter a length for the string that is divisible by the number of processes Number of vowels 27 

我真的不知道该怎么做才能修复它,只是我检查了我的代码是否存在逻辑错误,其中存在 none,即使它们是,它们也晚了很多,这意味着至少第一个 if 情况下的代码应该执行。

int main(int argc, char * argv[])
{
 printf("hello\n");
 int rank,m,size,num;
 MPI_Init(&argc,&argv);
 MPI_Comm_rank(MPI_COMM_WORLD,&rank);
 MPI_Comm_size(MPI_COMM_WORLD,&size);
 printf("from the other side.\n");
 char str[100];
 if (rank == 0 )
 {
  printf("Enter a length for the string that is divisible by the number of processes ");
  scanf("%d",&m);
  scanf("%s",str);
 }
.
.

如果相关,我是运行 Ubuntu 18.04.

您需要在最后一个 printf 之后添加一些 fflush(stdout); 以强制刷新文本。

printf文本中没有\n时,不会立即显示文本。

所以你应该写:

printf("Enter a length for the string that is divisible by the number of processes ");
fflush(stdout);
scanf("%d",&m);
....

或更简单:

puts("Enter a length for the string that is divisible by the number of processes ");
scanf("%d",&m);
....

puts是在一行上打印一条消息(它会创建一个新行)。而且它没有缓冲。

以防将来有人读到这篇文章,这是对 Matthieu 所说内容的补充。 代码应该是这样的

 if (rank == 0 )
 {
  printf("Enter a length for the string that is divisible by the number of processes \n");
    fflush(stdout);
.
.
.