两次通过后MPI Implimentation停止?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (56)

我对MPI很新,所以我不确定为什么这段代码没有按预期运行。我的想法是将一个整数传递给一个随机节点并递减它直到达到0.当我尝试运行它时,它将整数传递两次并停止。有人可以指出我正确的方向吗?谢谢!

if (rank == 0)
{
  potato = rand() % 100 + size; // generate a random number between the number of processors and 100
  sendTo = rand() % (size - 1) + 1; // generate a number (not 0) to represent the process to send the potato to

  MPI_Send(&potato, 1, MPI_INT, sendTo, 0, MPI_COMM_WORLD); // send the potato
}

else // any process other than 0
{

  MPI_Recv(&potato, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //receive potato

  if (potato == -1) // check for termination int
    return;

  --potato; // decrement potato

  if (potato != 0)
  {
    do
    {
      sendTo = rand() % (size - 1) + 1; // send to a process 1 through size - 1
    } while (sendTo == rank || sendTo == 0); // make sure it won't send the potato to itself or 0

    printf("Node %d has the potato, passing to node %d.\n", rank, sendTo);
    MPI_Send(&potato, 1, MPI_INT, sendTo, 0, MPI_COMM_WORLD);

  }

  else // potato == 0
  {
    printf("Node %d is it, game over.\n", rank);

    potato = -1;
    for (int i = 1; i < size; ++rank) // send termination message
      MPI_Send(&potato, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
  }
}

输出:

Potato: 44
Node 3 has the potato, Passing to node 2.
Node 2 has the potato, Passing to node 3.
提问于
用户回答回答于

你的代码缺少一些循环。在您的示例中,要使节点3第二次接收patato,MPI_Recv必须再次调用。

if (rank == 0)
{
  potato = rand() % 100 + size; // generate a random number between the number of processors and 100
  sendTo = rand() % (size - 1) + 1; // generate a number (not 0) to represent the process to send the potato to

  MPI_Send(&potato, 1, MPI_INT, sendTo, 0, MPI_COMM_WORLD); // send the potato
}

else // any process other than 0
{
  /* Here is the loop beginning, while patato is not -1, continue reading*/
  while (1)
  {
    MPI_Recv(&potato, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //receive potato

    if (potato == -1) // check for termination int
      return;

    --potato; // decrement potato

    if (potato != 0)
    {
      do
      {
        sendTo = rand() % (size - 1) + 1; // send to a process 1 through size - 1
      } while (sendTo == rank || sendTo == 0); // make sure it won't send the potato to itself or 0

      printf("Node %d has the potato, passing to node %d.\n", rank, sendTo);
      MPI_Send(&potato, 1, MPI_INT, sendTo, 0, MPI_COMM_WORLD);

    }

    else // potato == 0
    {
      printf("Node %d is it, game over.\n", rank);

      potato = -1;
      for (int i = 1; i < size; ++rank) // send termination message
        MPI_Send(&potato, 1, MPI_INT, i, 0, MPI_COMM_WORLD);

    }
  }
}

所属标签

可能回答问题的人

  • 人生的旅途

    10 粉丝484 提问5 回答
  • 无聊至极

    4 粉丝504 提问5 回答
  • 富有想象力的人

    4 粉丝0 提问4 回答
  • 嗨喽你好

    7 粉丝480 提问4 回答

扫码关注云+社区

领取腾讯云代金券