我第一次使用執行緒,每當被呼叫的函式需要非常大的陣列時,就會遇到一個奇怪的分段錯誤。
#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;
}
程式像這樣運行良好,但如果我dimension將陣列的值增加 10 倍,則會出現分段錯誤。有誰知道為什么會發生這種情況以及如何解決它?
uj5u.com熱心網友回復:
double p* = new double[dimension];
double v* = new double[dimension];
我認為這是因為編譯器定義的大小限制可能使用動態分配而編譯的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447437.html
