如何使用 MPI 发送和接收字符串

How to send and receive string using MPI

本文关键字:字符串 何使用 MPI      更新时间:2023-10-16

>我正在尝试使用 MPI 发送和接收字符串,但结果是无跳的。

发送功能:

MPI_Send(&result, result.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);

和 recv 功能:

    MPI_Recv(&result,      /* message buffer */
        128,                 /* one data item */
        MPI_CHAR,        /* of type char real */
        MPI_ANY_SOURCE,    /* receive from any sender */
        MPI_ANY_TAG,       /* any type of message */
        MPI_COMM_WORLD,    /* default communicator */
        &status);          /* info about the received message */

其中结果是字符串。

我没有收到任何错误,但程序不想完成。

std::string 的地址与底层 C 字符串的地址不同,因此发送应像这样固定:

MPI_Send(result.c_str(), result.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);

接收无法像您尝试的那样完成。您需要一个缓冲区(char数组),您将传递给MPI_Recv并在以后使用它来创建std::string实例。要获取收到的字符串的长度,请使用MPI_Get_count - 这应该沿着指向缓冲区的指针传递到构造函数std::string

为了避免预分配缓冲区并允许它接收任何大小的字符串,您应该调用 MPI_ProbeMPI_Get_count首先获取长度。知道长度后,您可以根据需要分配确切大小的缓冲区,然后才调用MPI_Recv

如果这听起来有点复杂,那么您可以考虑使用 BOOST MPI 包装器。

我遇到了类似的问题,我必须在 MPI C 中的两个进程之间传递字符串。与您的问题一致的解决方案如下:

MPI_Send(&result, strlen(result)+1, MPI_CHAR, 1, 0, MPI_COMM_WORLD); // Destination: Process 1

另一方面,进程 0 将具有以下MPI_Recv功能:

MPI_Recv(&result, 100, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // Source: Process 0 and considering 100 as the maximum string length

必须在标头中添加<string.h>