2

我将使用 发送许多消息MPI_Isend,但我不确定如何确保我的数据在收到之前是安全的,同时,不要用完所有可用的内存。

目前,我正在做这样的事情:

vector<int*> outbox;
vector<MPI_Request> stats;

void run()
{
   while (!done()) 
   {
       //some magic
       //...

       sendMsg(rand(), getRecipRank());
  }
}

void sendMsg(int n, int recipRank)
{
    //Need to gen n random integers and send it to proc with rank recipRank
    //Can't block until the numbers are reveived. 
    //So how do I make sure these numbers are safe until then?


    int* data = (int*)malloc(sizeof(int) * n);
    //fill the data array with random numbers here

    MPI_Request req;
    MPI_Isend(data, n, MPI_INT, recipRank, 0, MPI_COMM_WORLD, &req);

    //Keeping the pointer to the array to free it later
    outbox.push_back(data); //Does this help keep the data safe until they're received?
    stats.push_back(req);
}

然后我有另一个函数偶尔会通过stats向量来检查发送的状态。如果完成,则该函数释放请求和outbox.

我已经用少量消息对此进行了测试,它似乎有效,但我不确定它是否总是有效,或者我只是很幸运。

4

2 回答 2

2

看起来不错!如果你分配内存使用malloc没人会弄乱它,但你。既然不惹事,那就安全了。

这是通过使用更多内存来交错计算和通信的好模式。如果您想限制内存使用量,您可以为向量设置最大长度,outbox并在达到该长度时开始使用阻塞发送。

只是为了澄清:您的数据并不“更安全”,因为您将其推入 vector outbox,即使不这样做也是安全的。您将其推入向量以便稍后释放它。

于 2016-10-20T15:13:28.013 回答
0

这很好用,但你甚至不需要求助于 C- malloc

您可以安全地使用 C++ 结构,例如:

  • new[]中的指针std::vector<int*>
  • std::vector<std::unique_ptr<int[]>>(我更喜欢你的情况)
  • std::vector::data()向量中的向量。但是,为此请确保在请求完成之前,不要在提供调用内存的向量上调用任何非常量方法。

使用它是不安全的,或者std::vector<int[10]> outbox因为std::vector<std::array<int, 10>> outbox此内存将直接在发件箱向量内引用,这可能会在进一步调用push_back. 但这仅对 compile-time-known 很重要nstd::vector<std::unique_ptr<std::array<int, 10>>>会好起来的。

于 2016-10-20T18:08:53.373 回答