[英]Multithreading segmentation fault (for loop)
Why does the following code give me a segmentation fault: 为什么以下代码给我一个分段错误:
#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] << " ";
}
}
I know that the segmentation fault happens inside the for loop where the iterator is used, but I'm not sure why. 我知道分段错误发生在使用迭代器的for循环内,但是我不确定为什么。
vector<thread*> threads(size);
Declaration creates a vector with size
amount of default-initialized thread*
objects which are nullptr
. 声明创建一个向量,该向量的size
为nullptr
的默认初始化thread*
对象的size
。
Then with push_back
you insert additional non-null objects but the null ones remain there, and you dereference them when iterating over vector at the end. 然后使用push_back
插入其他非空对象,但空对象保留在那里,并在最后遍历vector时取消引用它们。
You should change the for
loop to read as below: 您应该将for
循环更改为以下内容:
for (int i = 0; i < size; ++i) {
thread *t = new thread(f, a[i], b[i], &c[i]);
threads[i] = t;
}
And before ending, you should delete
your heap-allocated thread
s. 在结束之前,您应该delete
分配给堆的thread
。
for (auto thread : threads)
delete thread;
Even better is to simply use: 更好的是简单地使用:
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();
By the way, you should pay attention to the compiler warnings. 顺便说一句,您应该注意编译器警告。 Change 更改
double f(double a, double b, double *c) { *c = a + b; }
to 至
void f(double a, double b, double *c) { *c = a + b; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.