多线程分段故障(for loop)

asy*_*Fan 0 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] << " ";                                 
   }
}
Run Code Online (Sandbox Code Playgroud)

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

dew*_*led 8

vector<thread*> threads(size);
Run Code Online (Sandbox Code Playgroud)

声明创建一个具有size默认初始化thread*对象数量的向量nullptr.

然后push_back插入其他非空对象,但空的对象保留在那里,并在最后迭代向量时取消引用它们.


Ard*_*kin 5

您应该将for循环更改为如下所示:

for (int i = 0; i < size; ++i) {
  thread *t = new thread(f, a[i], b[i], &c[i]);
  threads[i] = t;
}
Run Code Online (Sandbox Code Playgroud)

在结束之前,您应该为delete堆分配threads。

for (auto thread : threads)
  delete thread;
Run Code Online (Sandbox Code Playgroud)

更好的是简单地使用:

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();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您应该注意编译器警告。改变

double f(double a, double b, double *c) { *c = a + b; }
Run Code Online (Sandbox Code Playgroud)

void f(double a, double b, double *c) { *c = a + b; }
Run Code Online (Sandbox Code Playgroud)