我不喜欢仅仅为了做这个简单的事情而导入库的想法。所以这就是我所做的:
我认为没有理由让 MPI 了解对象的底层结构。所以我可以手动将其转换为缓冲区数组,并且由于接收器知道它需要一个 Node 结构,因此可以在另一侧重新创建对象。所以最初我定义了一个MPI_Contiguous 数据类型并发送它:
int size = (int) ((node.second.neighbors.size() + 1) * sizeof(int *));
MPI_Datatype datatype;
MPI_Type_contiguous(size, MPI_BYTE, &datatype);
MPI_Type_commit(&datatype);
MPI_Isend(&buffer, 1, datatype, proc_rank, TAG_DATA, MPI_COMM_WORLD, &request);
这是一个更通用的解决方案并且有效。
但由于结构包含int 和vector<int>,我决定创建一个int 缓冲区,第一个元素为node.id,重置为node.neighbors。另一方面,使用MPI_Iprobe(或同步MPI_Probe)和MPI_Get_count我可以重新创建节点结构。代码如下:
int *seriealizeNode(Node node) {
//allocate buffer array
int *s = new int[node.neighbors.size() + 1];
//set the first element = Node.id
s[0] = node.id;
//set the rest elements to be the vector elements
for (int i = 0; i < node.neighbors.size(); ++i) {
s[i + 1] = node.neighbors[i];
}
return s;
}
Node deseriealizeNode(int buffer[], int size) {
Node node;
//get the Node.id
node.id = buffer[0];
//get the vector elements
for (int i = 1; i < size; ++i) {
node.neighbors.push_back(buffer[i]);
}
return node;
}
我认为必须有一种更有效/更快的方式将 Node 转换为 int[] ,反之亦然。我想知道是否有人可以提供一些建议。
然后在发送方:
while (some_condition){
...
//if there is a pending request wait for it to finish and then free the buffer
if (request != MPI_REQUEST_NULL) {
MPI_Wait(&request, &status);
free(send_buffer);
}
// now send the node data
send_buffer = seriealizeNode(node.second);
int buffer_size = (int) (node.second.neighbors.size() + 1);
MPI_Isend(send_buffer, buffer_size, MPI_INT, proc, TAG_DATA, MPI_COMM_WORLD, &request);
...
}
在接收方方面:
int count = 0;
MPI_Iprobe(MPI_ANY_SOURCE, TAG_DATA, MPI_COMM_WORLD, &flag, &status);
if (flag) {
MPI_Get_count(&status, MPI_INT, &count);
int *s = new int[count];
MPI_Recv(s, count, MPI_INT, MPI_ANY_SOURCE, TAG_DATA, MPI_COMM_WORLD, &status);
Node node = deseriealizeNode(s, count);
free(s);
//my logic
}
现在它可以按预期工作了。