2017-09-24 104 views
0

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

#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()

回答

0

stdin通常从mpirun/mpiexec重定向到等级0

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

底线,我不认为你正在尝试是可以实现的。

+0

我正在使用openMPI。感谢您的回答,我在文档中发现: '-stdin, - stdin 要接收stdin的进程的MPI_COMM_WORLD等级。默认值是将stdin转发到MPI_COMM_WORLD等级0,但是此选项可用于将stdin转发到任何进程。指定none也是可以接受的,表示没有进程要接收标准输入。' 不幸的是,我看不到任何选项重定向到所有的队伍。我认为这将做我想要的。 无论如何,现在我知道发生了什么。谢谢。 –