#include <mpi.h>
#include<vector>
std::vector<std::vector<int>> inds;
int inds_size;
std::vector<int> inds_i_size;
if (myid == 0) {
//在进程0里获取inds
for (int i1 = 0; i1 < 2; ++i1) {
for (int i3 = 0; i3 < 4; ++i3) {
std::vector<int> ind{ i1, i3 };
inds.emplace_back(ind);
}
}
inds_size = inds.size();
inds_i_size.resize(inds.size());
for (int i = 0; i < inds.size(); ++i) {
inds_i_size[i] = inds[i].size();
for (int j = 0; j < inds[i].size(); ++j) {
std::cout << "inds[" << i << "][" << j << "]=" << inds[i][j] << ", ";
}
std::cout << std::endl;
}
}
MPI_Bcast(&inds_size, 1 * sizeof(int), MPI_BYTE, 0, MPI_COMM_WORLD);
//先广播inds的外层的大小
if (myid > 0)
inds_i_size.resize(inds_size);
//再广播inds的内层的向量的大小
MPI_Bcast(inds_i_size.data(), inds_i_size.size() * sizeof(int), MPI_BYTE, 0,
MPI_COMM_WORLD);
//然后在其他进程里开辟外层向量的空间大小,然后再开辟内层的向量的空间
if (myid > 0) {
inds.resize(inds_size);
for (int i = 0; i < inds.size(); ++i)
inds[i].resize(inds_i_size[i]);
}
//然后在其他进程里广播内层向量
for (int i = 0; i < inds.size(); ++i) {
MPI_Bcast(inds[i].data(), inds[i].size() * sizeof(int), MPI_BYTE, 0,
MPI_COMM_WORLD);
}
std::vector<std::vector<std::vector<int>>> inds_id(numprocs - 1); // except process 0
//从进程0发送inds给其他进程
for (int i = 0; i < inds.size(); ++i) {
if (myid == 0) {
int ret = MPI_Send(inds[i].data(), inds[i].size() * sizeof(int), MPI_BYTE,
i % (numprocs-1) + 1, i, MPI_COMM_WORLD);
std::cout << "MPI_Send ret=" << ret << ", process 0 send to process " << (i %
(numprocs - 1)) + 1 << " send: ";
for (int j = 0; j < inds[i].size(); ++j) {
std::cout << inds[i][j] << " ";
}
std::cout << std::endl;
}
if (myid == i % (numprocs - 1) + 1) {
std::vector<int> ind_recv(inds[i].size());
int ret = MPI_Recv(ind_recv.data(), ind_recv.size() * sizeof(int), MPI_BYTE,
0, i, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << "MPI_Recv ret=" << ret <<", process " << myid << " received from
process 0 : ";
for (int j = 0; j < ind_recv.size(); ++j) {
std::cout << ind_recv[j] << " ";
}
std::cout << std::endl;
inds_id[myid-1].emplace_back(ind_recv);
}
}
C++ MPI_Send, MPI_Recv 双重向量
于 2024-08-18 16:08:14 首次发布