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

Joh*_*ohn 3 c c++ mpi

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

发送功能:

MPI_Send(&result, result.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);
Run Code Online (Sandbox Code Playgroud)

和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 */
Run Code Online (Sandbox Code Playgroud)

结果是字符串.

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

pio*_*kuc 13

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

MPI_Send(result.c_str(), result.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);
Run Code Online (Sandbox Code Playgroud)

您尝试这样做时无法接收.您需要一个缓冲区(一个数组char),您将传递给MPI_Recv它并稍后使用它来创建std::string实例.要获得接收的字符串的长度,请使用MPI_Get_count- 这应该将指针传递给缓冲区到std::string构造函数.

为了避免预先分配缓冲区并允许它接收任何大小的字符串,你应该调用MPI_ProbeMPI_Get_count获得长度.知道了长度,您可以使用必要的确切大小来分配缓冲区,然后再调用MPI_Recv.

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

  • 你不应该使用MPI_Send(result.c_str(),result.size()+ 1,MPI_CHAR,0,0,MPI_COMM_WORLD); 为了包含字符串终止符号'\ 0'? (2认同)