对于刚接触 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;
}
对于 MPI 集体通信,everyone必须参加;每个人都必须调用 Bcast,或者 Allreduce,或者你有的东西。 (这就是为什么 Bcast 例程有一个参数指定“root”,或者谁在发送;如果只有发送者调用 bcast,则不需要这个。)每个人都调用广播,包括接收者;接收者不只是发布接收信息。
这样做的原因是集体操作可以让每个人都参与通信,这样你就可以陈述你想要发生的事情(每个人都获得一个进程的数据),而不是how它发生了(例如,根处理器在所有其他级别上循环并执行发送),因此存在优化通信模式的范围(例如,基于树的分层通信需要log(P)
步骤而不是P
P 过程的步骤)。