gpt4 book ai didi

c++ - 使用 OMP 进行多个 Eigen::Matrix 初始化:段错误

转载 作者:行者123 更新时间:2023-12-02 10:29:17 30 4
gpt4 key购买 nike

在以下最小示例中,我尝试在由 OMP 并行化的 for 循环中创建一些 Eigen::Matrix。每个矩阵都包含在循环中,因此线程之间没有数据共享或竞争条件。当线程数等于 1 时,代码可以完美运行,否则会出现段错误。令人难以置信的是,我得到大小为 600x600 的矩阵的段错误,而不是例如 599x599 或 601x601 或 1000x1000。任何帮助表示赞赏。谢谢 :)

#include <iostream>

#define EIGEN_DONT_ALIGN_STATICALLY
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <Eigen/Core>

#define SIZE 600
#define THREADS 2

int main(int argc, char *argv[]) {

// The following code always works for THREADS=1
// When THREADS!=1, there is a seg fault if SIZE=600.
// There is no seg fault when THREADS!=1 and SIZE=599 or SIZE=601

#pragma omp parallel for num_threads(THREADS)
for(int n=0; n<5; ++n){
Eigen::Matrix<double,SIZE,SIZE> mat = Eigen::Matrix<double,SIZE,SIZE>::Zero();
}

return 0;
}


最佳答案

问题来自 固定尺寸 和有限的堆栈大小 .确实,Matrix<double,SIZE,SIZE>在堆栈上分配,并且因为 SIZE相当大,它应该在大多数系统上分配 2.7 MiB,而堆栈大小通常设置为几 MiB(在大多数 Linux 平台上默认设置为 2 MiB)。您应该使用 Dynamic矩阵大小 反而。
the documentation了解更多信息:

The limitation of using fixed sizes, of course, is that this is only possible when you know the sizes at compile time. Also, for large enough sizes, say for sizes greater than (roughly) 32, the performance benefit of using fixed sizes becomes negligible. Worse, trying to create a very large matrix using fixed sizes inside a function could result in a stack overflow, since Eigen will try to allocate the array automatically as a local variable, and this is normally done on the stack.

关于c++ - 使用 OMP 进行多个 Eigen::Matrix 初始化:段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62966985/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com