在具有大型数组的函数上使用线程时出现分段错误 -C++
我是第一次使用线程,每当被调用的函数采用非常大的数组时,就会遇到奇怪的分段错误。
#include <iostream>
#include <thread>
#include <cmath>
const int dimension = 100000; // Dimension of the array
// Create a simple function of an array
void absolut(double *vec) {
double res = 0.;
for (int i = 0; i < dimension; i++) {
res += vec[i] * vec[i];
}
std::cout << std::sqrt(res) << std::endl;
}
int main() {
// Define arrays
double p[dimension], v[dimension];
for (int i = 1; i < dimension; i++) {
p[i] = 1./double(i);
v[i] = 1./double(i)/double(i);
}
// use multithreading
std::thread t1(absolut, p);
std::thread t2(absolut, v);
t1.join();
t2.join();
return 0;
}
程序像这样运行良好,但如果我将数组的维度增加 10 倍,则会出现分段错误。有谁知道为什么会发生这种情况以及如何解决它?
I am using threads for the first time and came across a weird segmentation error whenever the called function takes very large arrays.
#include <iostream>
#include <thread>
#include <cmath>
const int dimension = 100000; // Dimension of the array
// Create a simple function of an array
void absolut(double *vec) {
double res = 0.;
for (int i = 0; i < dimension; i++) {
res += vec[i] * vec[i];
}
std::cout << std::sqrt(res) << std::endl;
}
int main() {
// Define arrays
double p[dimension], v[dimension];
for (int i = 1; i < dimension; i++) {
p[i] = 1./double(i);
v[i] = 1./double(i)/double(i);
}
// use multithreading
std::thread t1(absolut, p);
std::thread t2(absolut, v);
t1.join();
t2.join();
return 0;
}
The program runs fine like this, but if I increase the dimension
of the arrays by a factor 10, then I get a segmentation fault. Does anybody know why this occurs and how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这可以编译,因为编译器定义的大小限制可能使用动态分配。
I think this compiles because of the compiler defined size limits maybe using dynamically allocation.