我使用 openmpi 和 linux mint,考虑以下示例:
#include <boost/mpi.hpp>
#include <iostream>
#include <string>
#include <boost/serialization/string.hpp>
namespace mpi = boost::mpi;
using namespace std;
int main()
{
mpi::environment env;
mpi::communicator world;
if (world.rank() == 0)
{
world.send(1, 0, std::string("3664010"));
while (1)
{
world.send(1, 0, std::string("3664012"));
sleep(1);
}
}
else
{
std::string msg;
string dst;
bool first = true;
while (1)
{
world.recv(0, 0, msg);
if (first) {dst = msg;first = false;}
std::cout << "slave received=" << dst << " msg=" << msg << std::endl;
}
}
return 0;
}
编译:mpic++ -std=c++0x test.cc -lboost_serialization -lboost_mpi
运行:mpirun -np 2 ./a.out
输出:从属接收=3664010 msg=3664010
从属接收=3664012 msg=3664012
从属接收=3664012 msg= 3664012
只有当所有消息的长度相等时,才会重现错误。例如,如果第二条消息是“3664012andmore”,一切正常:
slave received=3664010 msg=3664010
slave received=3664010 msg=3664012andmore
slave received=3664010 msg=3664012andmore
slave received=3664010 msg=3664012andmore
看起来 dst 和 msg 使用相同的内存缓冲区。只有当字符串长度不同时,它们才会开始使用不同的内存缓冲区。我使用以下解决方法(msg = string()) 告诉编译器 msg 已更改:
std::cout << "slave received=" << dst << " msg=" << msg << std::endl;
msg = string();
它工作正常。有没有更好的解决方案?谢谢你。