MPI忽略了cin

时间:2017-09-24 14:42:17

标签: c++ mpi cin

我写了以下代码。它打算从控制台读取数字(到data变量)并将其发送到所有其他进程。但cin >> data只是被忽略了。

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

using namespace std;

int main(int argc, char* argv[]) {
  int rank, n;
  int i;
  MPI_Status status;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &n);
  int data = 322; // magic number 322 just for initialisation
  if (rank == 0)
  {
    cout << "From which process do you want to transfer data?" << endl;
    cin >> i;
    MPI_Send(&i, 1, MPI_INT, rank+1, 0, MPI_COMM_WORLD);
  }
  else
  {
    MPI_Recv(&i, 1, MPI_INT, rank-1, 0, MPI_COMM_WORLD, &status);

    if (rank < n - 1)
      MPI_Send(&i, 1, MPI_INT, rank+1, 0, MPI_COMM_WORLD);

    if(rank == i) {
      cout << "Process #"<< rank <<" waiting data to send. Please enter." << endl;
      cin >> data; //doesn't work

      for(int j = 0; j < n; j++)
        if(j != i)
          MPI_Send(&data, 1, MPI_INT, j, 7, MPI_COMM_WORLD);
    }
    else {
        int pata;
        MPI_Recv(&pata, 1, MPI_INT, i, 7, MPI_COMM_WORLD, &status);
        cout << "Process "<< rank <<" received data (" << pata << ") from process #" << i << endl;
    }
  }
  MPI_Finalize( );
}

控制台看起来像:

From which process do you want to transfer data?
2
Process #2 waiting data to send. Please enter.
Process 1 received data (322) from process #2
Process 3 received data (322) from process #2

我已经尝试过cin.clear()cin.ignore()

1 个答案:

答案 0 :(得分:0)

stdin通常会从mpirun / mpiexec重定向到排名0

可能有选项(取决于您正在运行的实施)重定向到您选择的等级,和/或重定向到所有等级。

最重要的是,我不认为你所尝试的是可以实现的。