在具有大型数组的函数上使用线程时出现分段错误 -C++

发布于 2025-01-15 00:03:31 字数 847 浏览 3 评论 0原文

我是第一次使用线程,每当被调用的函数采用非常大的数组时,就会遇到奇怪的分段错误。

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦爱 2025-01-22 00:03:31
double p* = new double[dimension];
double v* = new double[dimension];

我认为这可以编译,因为编译器定义的大小限制可能使用动态分配。

double p* = new double[dimension];
double v* = new double[dimension];

I think this compiles because of the compiler defined size limits maybe using dynamically allocation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文