我无法让 MPI_Isend 发送到随机目的地。如果我对目的地进行硬编码,它工作正常,但如果我尝试生成一个随机的目的地,它就不会。这是一些相关代码:
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
srand48(myid);
request=MPI_REQUEST_NULL;
if(myid == 0){
buffer=drand48();
do {
destination=lrand48() % numprocs;
} while (destination == 0); //Prevent sending to self
MPI_Isend(&buffer,1,MPI_DOUBLE,destination,1234,MPI_COMM_WORLD,&request);
}
else if (myid == destination) {
MPI_Irecv(&buffer,1,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&request);
}
if(myid == 0){
printf("processor %d sent %lf to %d\n",myid,buffer,destination);
}
else {
printf("processor %d got %lf\n",myid,buffer);
}
我可以用 mpicc main.c
编译得很好 当我用 mpirun -np 4 ./a.out
运行程序时,输出是:
processor 0 sent 0.170828 to 2
processor 1 got 0.000000
processor 2 got 0.000000
processor 3 got 0.000000
例如,如果我将目的地硬编码为 2,那么我会得到预期的输出:
processor 0 sent 0.170828
processor 1 got 0.000000
processor 2 got 0.170828
processor 3 got 0.000000
最佳答案
MPI_Isend
和MPI_Irecv
发起相应的非阻塞操作。在您将返回的 request
句柄传递给 MPI_Wait
或 MPI_Test
系列的函数之前,无法保证它们会完成(如果测试使用函数时,请求的完成状态将在 bool 变量中传回,只要 bool 标志保持为假,请求的完成状态就不会完成。
但是您的代码存在概念性问题。 MPI 是一种分布式内存范例——每个 MPI 等级实际上都存在于其单独的地址空间中(尽管标准没有严格要求,但实际上所有 MPI 实现都提供了这一点)。因此,将 destination
设置为 0 级不会神奇地将其值转移到其他进程。您可以首先广播该值或向所有其他等级发送特殊的“空”消息,例如:
if (myid == 0) {
MPI_Request reqs[numprocs];
buffer=drand48();
do {
destination=lrand48() % numprocs;
} while (destination == 0); //Prevent sending to self
for (i = 1; i < numprocs; i++) {
if (i == destination)
MPI_Isend(&buffer,1,MPI_DOUBLE,i,1234,MPI_COMM_WORLD,&reqs[i]);
else
// Send an empty message with different tag
MPI_Isend(&buffer,0,MPI_DOUBLE,i,4321,MPI_COMM_WORLD,&reqs[i]);
}
reqs[0] = MPI_REQUEST_NULL;
MPI_Waitall(numprocs, reqs, MPI_STATUSES_IGNORE);
printf("processor %d sent %lf to %d\n",myid,buffer,destination);
}
else {
MPI_Status status;
MPI_Recv(&buffer,1,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
if (status.MPI_TAG == 1234)
printf("processor %d got %lf\n",myid,buffer);
}
通过广播,代码如下所示:
request=MPI_REQUEST_NULL;
if (myid == 0) {
buffer=drand48();
do {
destination=lrand48() % numprocs;
} while (destination == 0); //Prevent sending to self
MPI_Bcast(&destination,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Isend(&buffer,1,MPI_DOUBLE,destination,1234,MPI_COMM_WORLD,&request);
}
else {
MPI_Bcast(&destination,1,MPI_INT,0,MPI_COMM_WORLD);
if (myid == destination) {
MPI_Irecv(&buffer,1,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&request);
}
}
MPI_Wait(&request, MPI_STATUS_IGNORE);
if (myid == 0) {
printf("processor %d sent %lf to %d\n",myid,buffer,destination);
}
else {
printf("processor %d got %lf\n",myid,buffer);
}
关于c - MPI_Isend 到随机目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964458/