多线程分段故障(for loop)

时间:2018-03-16 11:17:28

标签: c++ multithreading vector 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] << " ";                                 
   }
}

我知道分段错误发生在使用迭代器的for循环中,但我不确定原因。

2 个答案:

答案 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; }