为什么以下代码会给我一个分段错误:
#include<iostream>
#include<thread>
#include<vector>
using namespace std;
double f(double a, double b, double* c) {
*c = a + b;
}
int main() {
vector<double> a ={1,2,3,4,5,6,7,8};
vector<double> b ={2,1,3,4,5,2,8,2};
int size = a.size();
vector<double> c(size);
vector<thread*> threads(size);
for (int i = 0; i < size; ++i) {
thread* t = new thread(f, a[i], b[i], &c[i]);
threads.push_back(t);
}
for (vector<thread*>::iterator it = threads.begin(); it != threads.end(); it++) {
(*it)->join();
}
cout << "Vector c is: ";
for (int i =0; i < size; ++i) {
cout << c[i] << " ";
}
}
我知道分段错误发生在使用迭代器的for循环中,但我不确定原因。
答案 0 :(得分:8)
vector<thread*> threads(size);
声明会创建一个向量,size
个默认初始化thread*
个对象为nullptr
。
然后使用push_back
插入其他非空对象,但是空对象仍然存在,并且在最后迭代向量时取消引用它们。
答案 1 :(得分:4)
您应该将for
循环更改为如下所示:
for (int i = 0; i < size; ++i) {
thread *t = new thread(f, a[i], b[i], &c[i]);
threads[i] = t;
}
在结束之前,你应该delete
你的堆分配thread
s。
for (auto thread : threads)
delete thread;
更好的是简单地使用:
vector<thread> threads(size);
for (int i = 0; i < size; ++i)
threads[i] = thread(f, a[i], b[i], &c[i]);
for (auto& thread : threads)
thread.join();
顺便说一下,你应该注意编译器的警告。变化
double f(double a, double b, double *c) { *c = a + b; }
到
void f(double a, double b, double *c) { *c = a + b; }