1

我无法让 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
4

1 回答 1

1

MPI_IsendMPI_Irecv 启动相应的非阻塞操作。request无法保证在您将返回的句柄传递给MPI_Waitor家族的函数之前它们会完成MPI_Test(如果使用了测试函数,则请求的完成状态会在布尔变量中传回,并且它不完整因为布尔标志保持为假)。

不过,您的代码存在概念性问题。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);
}
于 2013-02-19T19:17:07.313 回答