我正在尝试在超立方体
中广播进程 0 中充满了 1 的矢量int main(int argc, char **argv) {
int myRank, nProc;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
MPI_Comm_size(MPI_COMM_WORLD, &nProc);
MPI_Request request;
MPI_Status status;
MPI_Barrier(MPI_COMM_WORLD);
double start = MPI_Wtime();
std::vector<int> vector(100, 0);
if (myRank == 0) {vector = std::vector<int>(100, 1);}
//Broadcast in a hypercube
int dimension = log2(nProc);
for (int step = 0 ; step < dimension ; step++) {
std::bitset<6> tmpRank(myRank);
if (tmpRank >> step == 0) { //source
int neighbor = static_cast<int>(tmpRank.flip(step).to_ulong()); //The neighbor of a source at the step i is the i_th bit flipped, re-converted to int in order to send
MPI_Send(vector.data(), vector.size(), MPI_INT, neighbor, 0, MPI_COMM_WORLD);
}
else { //destination ( if(rank >> step == 1) )
//MPI_Status status;
MPI_Irecv(vector.data(), vector.size(), MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &request);
}
}
//
MPI_Barrier(MPI_COMM_WORLD);
double end = MPI_Wtime();
std::cout << "I am process " << myRank << " last element of my vector after broadcast is " << vector.back() << std::endl;
if (myRank==0) std::cout << " operation time : " << end-start << "[s]" << std::endl;
MPI_Finalize();
}
我有输出:
I am process 0 last element of my vector after broadcast is 1 operation time : 3.40939e-05[s] I am process 1 last element of my vector after broadcast is 1 I am process 2 last element of my vector after broadcast is 1 I am process 3 last element of my vector after broadcast is 0
为什么最后一个进程没有收到向量?该错误必须来自发送和接收,但是我不知道应该使用哪个功能(发送,发送,接收,发送)。 谢谢
答案 0 :(得分:3)
您必须显式完成所有无阻塞的通信(在您的情况下为MPI_Irecv
),然后才能访问任何参与的数据。这意味着您无法完成数据转发或打印。适当使用MPI_Wait
,MPI_Test
或any
/ some
/ all
的任何变体。
如您的示例所示,如果您不需要无阻塞通信,请改为使用阻塞通信(即MPI_Recv
)。
实际上,在可能的情况下,MPI_Bcast
使用集合而不是点对点。除非您想学习或真正知道自己在做什么,否则实施自己的广播不是一个好主意。