【发布时间】:2018-02-21 15:59:46
【问题描述】:
大家好,我是 MPI 的新手,我在网站上搜索发现有一种方法可以收集动态大小的矢量,并结合收集大小然后收集 v。 但是我的代码有问题,这是我正在运行的测试,以查看我是否正确执行。
int main(int arg, char** argvs) {
MPI_Init(&arg, &argvs);
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<int> vectordata;
if (rank == 1)
vectordata.push_back(2);
if (rank == 2) {
vectordata.push_back(1);
vectordata.push_back(5);
}
int *counts = new int[size];
int nelements = (int)vectordata.size();
// Each process tells the root how many elements it holds
MPI_Gather(&nelements, 1, MPI_INT, counts, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Displacements in the receive buffer for MPI_GATHERV
int *disps = new int[size];
// Displacement for the first chunk of data - 0
for (int i = 0; i < size; i++)
disps[i] = (i > 0) ? (disps[i - 1] + counts[i - 1]) : 0;
// Place to hold the gathered data
// Allocate at root only
vector<int> alldata;
if (rank == 0)
// disps[size-1]+counts[size-1] == total number of elements
alldata = vector<int>(disps[size - 1] + counts[size - 1]);
// Collect everything into the root
MPI_Gatherv(vectordata.data(), nelements, MPI_INT,
alldata.data(), counts, disps, MPI_INT, 0, MPI_COMM_WORLD);
cout << alldata.size() << endl;
cout << alldata[0] << endl;
cout << alldata[1] << endl;
cout << alldata.back() << endl;
MPI_Finalize();
}
第一个 cout 应该打印 3,而不是打印:
0
0
3
最后 3 个 cout 打印:
2
1
5
但是在打印后它崩溃说:调试断言失败!向量下标超出范围。
我认为这与位移有关,但我不确定是什么,如果有人可以向我解释我计算 disps[i] 的行,因为我从以前的答案中得到它,我不完全明白它。
提前谢谢你。
【问题讨论】:
标签: c++ parallel-processing mpi