【发布时间】:2017-02-09 01:26:04
【问题描述】:
我正在尝试通过使用 std::thread 来加速 for 循环。该循环遍历由数百万个项目组成的列表。我将每次迭代都分配给不同的线程。
4047 次迭代后,它停止运行并抛出 terminate called without an active exception Aborted (core dumped)
我相信这个错误通常是由于线程没有正确连接引起的(如本网站其他问题所述)。但是,我确实有一个函数可以在我的 for 循环结束时加入所有线程。因为没有达到连接功能,我怀疑真正的问题是创建了太多线程。这是我第一次涉足 lambdas 和多线程,我不确定如何限制 for 循环内一次创建的线程数。
我的代码如下:
std::mutex m;
std::vector<std::thread> workers;
for ( ot.GoToBegin(), !ot.IsAtEnd(); ++ot ) // ot is the iterator
{
workers.push_back(std::thread([test1, test2, ot, &points, &m, this]()
{
// conditions depending on the current ot are checked
if ( test1 == true ) return 0; // exit function
if ( test2 == true ) return 0;
// ...etc, lots of different checks are performed..
// if conditions are passed save the current ot
m.lock();
points.push_back( ot.GetIndex() );
m.unlock();
}));
} // end of iteration
std::for_each(workers.begin(), workers.end(), [](std::thread &t)
{
t.join(); // join all threads
});
任何帮助将不胜感激
【问题讨论】:
-
创建数百万个线程不会很漂亮 - 我建议查看线程池。
-
该问题的解决方案是拥有一个连接所有线程的函数。如上所述,我已经包含了一个连接函数,用于在 for 循环完成时连接所有线程
标签: c++ linux multithreading c++11