如何使用指向浮点块的指针复制构造一个 std::vector 并将其传递给线程?

How do I copy construct an std::vector with a pointer to block of floats and pass it to a thread?

我需要按值将一组浮点数传递到线程中,这些浮点数是第三方库返回的指针。像这样:

void TestThread(std::vector<float> data)
{
  std::cout << data.size();
}

void Thready ()
{
  vector<thread> threads(10);  // this actually varies at runtime.

  for (int i = 0; i < 10; i++)
  {
      float* data = HeapsOfFloats();
      int numberOfFloats = NumberOfFloats();
      std::vector<float> dataVector(data, data + numberOfFloats);
      threads[i] = std::thread::thread([&]{TestThread(dataVector)});
  }

  for (int t = 0; t < 10; t++) threads[t].join();
}

循环 1-n 次迭代后,我的程序崩溃了。

编辑:您正在通过引用(对对象)捕获向量,如果您幸运的话并且 lambda 中的函数调用已经复制了它 - 如果您不幸的话,它会在循环迭代结束后被销毁- 没有什么可复制的,你会崩溃。鉴于你 do 无论如何都想使用一个副本,我建议通过复制到 lambda 中捕获它,然后通过 ref:

传递它
void TestThread(const std::vector<float>& data)
{
  std::cout << data.size();
}

void Thready ()
{
  vector<thread> threads(10);  // this actually varies at runtime.

  for (int i = 0; i < 10; i++)
  {
      float* data = HeapsOfFloats();
      int numberOfFloats = NumberOfFloats();
      std::vector<float> dataVector(data, data + numberOfFloats);
      threads[i] = std::thread::thread([dataVector]{TestThread(dataVector)});
  }

  for (int t = 0; t < 10; t++) threads[t].join();
}

奖励:你的代码(和我的)会产生两份浮点数据副本,但如果你可以用 c++14 编写,你至少可以少一份副本:

...
 threads[i] = std::thread::thread([dataVector(std::move(dataVector))]{TestThread(dataVector)});
...

对于 C++14 之前的解决方案,请查看 here 或将您的向量包装在 smth 中,如 shared_ptr 这样复制起来会更便宜


我不认为你抓取浮动的方式有什么问题(如果你产生了太多的线程)。

但是我认为您的问题出在其他地方:您在每次迭代时都在破坏线程,但是如果您不关心它们并且不打算以后使用线程句柄,它们会在迭代结束时 have to be manually detached or joined to avoid termination, sometimes you are lucky and they run to termination before your loop cycle ends, sometimes - you are not. Just consider detachhave to be manually detached or joined to avoid termination, sometimes you are lucky and they run to termination before your loop cycle ends, sometimes - you are not. Just consider detach =14=]