我正在尝试使用std::thread来加速for循环。该循环遍历由数百万个项目组成的列表。我将每个迭代分配给不同的线程。
在4047次迭代之后,它停止运行并抛出terminate called without an active exception Aborted (core dumped)
我认为这个错误通常是由于线程没有被正确连接引起的(正如本网站上的其他问题所述)。但是,我确实有一个函数可以在for循环的末尾加入所有线程。因为没有达到连接函数,所以我怀疑真正的问题是创建了太多的线程。这是我第一次尝试lambda和多线程,我不确定如何限制在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
});任何帮助都将不胜感激
发布于 2017-02-09 11:29:15
因为你每次都会在相同的迭代中得到错误,所以原因并不在于"join“本身。系统上每个进程的线程数很可能受到4096个或类似数量的限制,请参见Maximum number of threads per process in Linux?
当您创建线程号4047左右时,std::thread的构造函数抛出一个异常,并且您永远不会到达"join“语句。
我建议您保留一个不是std::tread(s)的向量,而是std::future(s)的向量。代码可能大致如下所示:
typedef std::future<int> Future;
std::vector<Future> results;
for (...) {
results.emplace_back( std::async(std::launch::async,
[...](){ /* roughly same code as in your thread function */ }) );
}
for ( Future& result : results) {
auto value = result.get(); //waits for the task to finish
// process your values ...
}未来依赖于内部线程池,因此您不会耗尽线程。这些未来将在线程可用时异步执行。
https://stackoverflow.com/questions/42126676
复制相似问题