MPI 忽略 cin
MPI ignores 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()
。
stdin
通常从 mpirun
/mpiexec
重定向到排名 0
.
可能有选项(取决于您使用的是哪种实现 运行)重定向到您选择的等级,and/or 重定向到所有等级。
最重要的是,我不认为你正在尝试的是可以实现的。
我写了下面的代码。它打算从控制台读取数字(到 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()
。
stdin
通常从 mpirun
/mpiexec
重定向到排名 0
.
可能有选项(取决于您使用的是哪种实现 运行)重定向到您选择的等级,and/or 重定向到所有等级。
最重要的是,我不认为你正在尝试的是可以实现的。