2017-09-24 102 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也是可以接受的,表示沒有進程要接收標準輸入。' 不幸的是,我看不到任何選項重定向到所有的隊伍。我認爲這將做我想要的。 無論如何,現在我知道發生了什麼。謝謝。 –