我试图通过使用std::thread
加速for循环。循环遍历包含数百万项目的列表。我给每个迭代到不同的线程。C++线程不加入“终止调用没有活动异常”
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
});
任何帮助,将不胜感激
可能重复的[C++终止调用没有活动异常](http://stackoverflow.com/questions/7381757/c-terminate-called-without-an-active-exception) –
创建数百万个线程不会要漂亮 - 我会建议看看线程池。 –
该问题的解决方案是具有一个连接所有线程的函数。如上所述,我已经包含一个连接函数来加入所有线程完成for循环 – jla