C ++ std :: thread与类成员的交互

时间:2019-02-19 16:05:24

标签: c++ multithreading vector

考虑以下代码,这是我尝试做的事情的简化版本:

#include <iostream>
#include <vector>
#include <thread>

#define NTHREAD 4

class Worker {
public:
  std::vector<double> stored_val;

  Worker(): stored_val() {}

  Worker(const Worker& t) {this->stored_val = t.stored_val;}

  void Test() {
    for (int it=0; it<3; ++it)
      stored_val.push_back(it);
  }
};

int main() {
  std::vector<Worker> workers;
  std::vector<std::thread> threads;

  for (int iThread=0; iThread<NTHREAD; ++iThread) {
    workers.push_back(Worker());
    threads.push_back(std::thread(&Worker::Test, &workers.back()));
  }

  for (auto& it: threads)
    it.join();

  for (auto const& w: workers)
    for (size_t it=0; it<w.stored_val.size(); ++it)
      std::cout << "it " << it << " : " << w.stored_val[it] << std::endl;
}

这是在执行开始时进行段错误(但是奇怪的是,在gdb中没有段错误)。 当stored_val是简单的doubleNTHREAD1时,一切工作都很好。有办法使这项工作吗?

解决方案

正确的是,阅读评论后,完成这项工作的方法是:

  for (int iThread=0; iThread<NTHREAD; ++iThread) {
    workers.push_back(Worker());
    //threads.push_back(std::thread(&Worker::Test, &workers.back()));
  }

  for (std::vector<Worker>::iterator w=workers.begin(); w!=workers.end(); ++w) {
    threads.push_back(std::thread(&Worker::Test, w));
  }

因为那样您确定矢量的地址不会改变。谢谢!

0 个答案:

没有答案