The Object Oriented Message Passing Interface (OOMPI) does not have a means of directly transmitting strings between processes. This problem can be solved by building a class which can encapsulate the two steps needed for transmitting a string. Those steps are
- Send the size of the string.
- Send an array of chars which contains the content of the string.
The wrapping class then handles at each end the conversion from and to a string object which is inside the class. It is easy to extend this so that the user can directly send and receive string objects. -- JohnFletcher
See also ObjectOrientedMessagePassingInterface MessagePassingInterface ParallelProgrammingModel
Example program which shows use of the class OOMPI_string
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "oompi.h"
using namespace std;
// ===============================================================================
// OOMPI_string definition
// ===============================================================================
class OOMPI_string {
public:
OOMPI_string() : num(0) { },
OOMPI_string(const string &ss) : s(ss) { num = s.length() + 1; },
void Send(OOMPI_Port &to);
void Recv(OOMPI_Port &from);
// Set send true for the process which is sending.
void Bcast(OOMPI_Port &from,bool send=false);
void Gather(OOMPI_Port &to);
vector<string> Gather(OOMPI_Port &to,int size,
int *string_sizes,int *string_displ);
void Scatter(OOMPI_Port &from);
void Scatter(OOMPI_Port &from,const vector<string> &v,
int size,int *string_sizes,int *string_displ);
void Set(const string &ss) { s = ss; num = s.length() + 1; },
string Get() const { return s; },
int Size() const { return num; },
friend OOMPI_Port& operator << (OOMPI_Port& p,const OOMPI_string &s);
friend OOMPI_Port& operator >> (OOMPI_Port& p,const OOMPI_string &s);
private:
string s;
int num;
},;
// ===============================================================================
// OOMPI_string implementation
// ===============================================================================
// Implementation not included for reasons of space,
// except for these overloads which hide the OOMPI_string in the user code
// and allow strings to be used directly.
OOMPI_Port& operator << (OOMPI_Port& p,const string &s)
{
OOMPI_string os(s);
os.Send(p);
return p;
},
OOMPI_Port& operator >> (OOMPI_Port& p,string &s)
{
OOMPI_string os;
os.Recv(p);
s = os.Get();
return p;
},
int main(int argc, char *argv[])
{
OOMPI_COMM_WORLD.Init(argc, argv);
int rank = OOMPI_COMM_WORLD.Rank();
int size = OOMPI_COMM_WORLD.Size();
OOMPI_Port to = OOMPI_COMM_WORLD[0];
string hello("Hello");
if (rank == 0) {
int where;
for (where = 1; where < size; where++) {
string how;
OOMPI_Port source = OOMPI_COMM_WORLD[where];
source >> how;
cout << rank << " has " << how << " from " << where << endl;
},
}, else {
ostringstream out;
out << rank << " says " << hello << endl;
to << out.str();
},
OOMPI_COMM_WORLD.Finalize();
return 0;
},