我正在尝试使用MPI_Bcast从根节点向所有其他节点广播消息.但是,每当我运行这个程序时,它总是挂起.有人知道它有什么问题吗?
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
int rank;
int buf;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(rank == 0) {
buf = 777;
MPI_Bcast(&buf, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
else {
MPI_Recv(&buf, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
printf("rank %d receiving received %d\n", rank, buf);
}
MPI_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*rsi 129
对于刚接触MPI的人来说,这是一个常见的混淆源.您不用于MPI_Recv()接收广播发送的数据; 你用MPI_Bcast().
例如,你想要的是这个:
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
int rank;
int buf;
const int root=0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(rank == root) {
buf = 777;
}
printf("[%d]: Before Bcast, buf is %d\n", rank, buf);
/* everyone calls bcast, data is taken from root and ends up in everyone's buf */
MPI_Bcast(&buf, 1, MPI_INT, root, MPI_COMM_WORLD);
printf("[%d]: After Bcast, buf is %d\n", rank, buf);
MPI_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于MPI集体沟通,每个人都必须参与其中; 每个人都必须打电话给Bcast,或Allreduce,或者你有什么.(这就是为什么Bcast例程有一个参数指定"root",或者谁正在发送;如果只有发送者叫bcast,你就不需要这个.)每个人都调用广播,包括接收者; 接收者不只是发布接收.
这样做的原因是集体操作可能涉及通信中的每个人,因此您可以说明您想要发生的事情(每个人都获得一个进程的数据)而不是它是如何发生的(例如,根处理器循环遍及所有其他级别并且发送),以便有优化通信模式的余地(例如,基于树的分层通信采用log(P)步骤而不是PP过程的步骤).