C++线程未加入"Termination called without active exception"

C++ thread not joining "Termination called without active exception"

本文关键字:called without active exception Termination C++ 线程      更新时间:2023-10-16

我正在尝试通过使用 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
});

任何帮助将不胜感激

由于您每次都在同一迭代中收到错误,因此原因不在于"join"本身。最有可能的是,系统上每个进程的线程数受到 4096 或类似数量的限制,请参阅 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 ...
}

将来依赖于内部线程池,因此不会耗尽线程。这些期货将在线程可用时异步执行。