gpt4 book ai didi

c - "MPI_Bcast"er 在运行时

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:13 25 4
gpt4 key购买 nike

在运行时决定广播者的情况下,如何执行 MPI_Bcast?这种情况下如何指定根节点?

我正在尝试在数组中搜索不同的数字。如果一个节点找到了这个号码,那么它应该将它的位置广播给所有其他节点。但是,由于我事先不知道查找器,“根”值应该在什么地方:

int MPI_Bcast ( void *buffer, int count, MPI_Datatype datatype, 
int root, MPI_Comm comm );

最佳答案

在进入集体之前,每个人都必须就“root”达成一致,因此必须事先进行一些协作。这是一种直接的方法——每个人都发送一个标志,指示他们是否拥有相关数据,然后每个人都可以同意从谁那里接收数据。这使您可以处理存在多个可能的发件人或没有发件人的情况。

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

int main(int argc, char **argv) {
int rank, size, ierr;
int bcaster;
int bcasterflag, *allflags;
int consensus;
int globaldata, mydata;

ierr = MPI_Init(&argc, &argv);
ierr|= MPI_Comm_size(MPI_COMM_WORLD,&size);
ierr|= MPI_Comm_rank(MPI_COMM_WORLD,&rank);

if (argc != 2) {
if (rank == 0) fprintf(stderr,"Usage: %s rank-to-broadcast\n",argv[0]);
MPI_Abort(MPI_COMM_WORLD,1);
}

bcaster = atoi(argv[1]);
if (bcaster < 0 ) bcaster = 0;
if (bcaster >= size) bcaster = size-1;

/* pretend the processes didn't all know the above and had to
* rely solely on local info to decide the broadcaster
*/

bcasterflag = 0; /* not the broadcaster yet */

mydata = rank*rank; /* the local data */
if (mydata == bcaster*bcaster) {
bcasterflag = 1;
globaldata = mydata;
}


/* collect these local decisions */

allflags = (int *)malloc(size * sizeof(int));
ierr = MPI_Allgather(&bcasterflag, 1, MPI_INT,
allflags, 1, MPI_INT, MPI_COMM_WORLD);

consensus = -1;
for (int i=0; i<size; i++)
if (allflags[i] != 0) consensus = i;

if (consensus == -1) {
if (rank == 0) {
fprintf(stderr,"Error: no one found to do the broadcast.\n");
}
} else {
ierr = MPI_Bcast(&globaldata, 1, MPI_INT, consensus, MPI_COMM_WORLD);
}

printf("%d: Received data %d from %d\n",
rank, globaldata, consensus);

return 0;
}

关于c - "MPI_Bcast"er 在运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com