如何使用 MPI 发送和接收字符串
How to send and receive string using MPI
>我正在尝试使用 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_Probe
并MPI_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>
。
相关文章:
- 接收字符串并使用它来调用方法C++
- 将 NULL 与 C 的字符* 字符串一起使用
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 对函数的 out 字符串参数使用 swap 与赋值
- 修改向量中的字符串?(不使用循环)
- 不带连续 1 的位字符串,使用自上而下的 DP
- 包括<字符串>,使用不完整的类型"std::string"
- MSVC UTF8字符串编码使用了不正确的代码点
- 在字符串中使用变量
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- 如何比较C 中的两个字符串并使用默认功能
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 将find_last_of与字符串C++一起使用
- 如何在处理C++字符串时使用内存集
- 在 c++ 中将 find_first_of 与字符串一起使用,而不是一组预定义字符
- C++17 std::basic_string_view 会使 C 字符串的使用无效吗?
- 检查字符串是否使用STD :: MAP包含重复
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- C 代码cout打印而不是等待在字符串中使用它
- 如何将adjacent_find与字符串C++一起使用