【发布时间】:2017-11-29 06:22:42
【问题描述】:
我正在尝试并行计算向量的 norm2(可变大小)。我的方法是首先将向量分散在处理器中,计算每个子向量的平方和总和,然后减少结果并应用平方根。
这是我的代码:
#include <mpi.h>
#include <vector>
#include <iostream>
#include <cmath>
double SquareSum(std::vector<double> & v) {
double res;
for (std::vector<double>::iterator it = v.begin(); it != v.end(); it++){
if (*it){
res += (*it)*(*it);
}
else{
it++;
}
}
return res;
}
int main(int argc, char *argv[]){
std::vector<double> numbers;
double val;
while (std::cin >> val) numbers.push_back(val);
MPI_Init(&argc,&argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
unsigned numbers_count = numbers.size();
MPI_Bcast(&numbers_count, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
unsigned local_share = numbers_count / size; // local_share is the floor function of numbers.size() / number of process
if (numbers_count % size > 0){
++local_share; // if size is not a multiple of numbers.size() add 1 to local_share in order to make it "fit"
}
if (rank == 0){
numbers.resize(local_share*size); //resize numbers by adding null empty spot if necessary
}
//std::cout << "I'm" << rank << std::endl;
std::vector<double> local(local_share);
MPI_Scatter(&numbers, local_share, MPI_DOUBLE, &local, local_share, MPI_DOUBLE, 0, MPI_COMM_WORLD);
double par_sum = SquareSum(local);
double sum = 0;
MPI_Reduce(&par_sum, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0){
std::cout << "norm : " << std::sqrt(sum);
}
MPI_Finalize();
return 0;
}
当我尝试执行程序时出现此错误:
“mpiexec 注意到节点笔记本电脑上 PID 9823 的进程等级 2 在信号 11 上退出(分段错误)。”
我想分散有问题,但我不知道是什么。
感谢您的帮助
【问题讨论】:
-
&numbers和&local是向量对象的控制结构的地址,而不是它们包含的数据。请改用&numbers[0]和&local[0]。 -
我更改了代码,我有同样的错误。但我做了一些研究,可能是由于记忆力不足。 (类似于 addind 交换)