C++线程未加入"Termination called without active exception"
C++ thread not joining "Termination called without active exception"
我正在尝试通过使用 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 ...
}
将来依赖于内部线程池,因此不会耗尽线程。这些期货将在线程可用时异步执行。
相关文章:
- dynamic_cast without RTTI
- Qt - QQuickWidget setSource without freezing UI
- "in-situ without memory allocation" 字符串的愚蠢实现意味着什么?
- "Called Object Type is Not a Function or Pointer" 与 typedef 和类
- C++线程"Call to non-static member function without an object argument"
- "terminate called after throwing an instance of std::invalid_argument' what(): stoi ?"
- 使用 QMediaPlayer 时出现"QWidget::paintEngine: Should no longer be called"
- 错误"pure virtual method called",当此方法已被覆盖时
- "How to make a recursive call for palindrom numbers without reverse function in c++?"
- 程序在VS2017上以"abort() has been called"错误结束
- 谷歌模拟 - 怎么说"function must be called ONCE with a certain parameter but ok to be called many times with
- 使用 -march 编译会导致线程说"pure virtual method called"
- 如何使用 std::transform with container without push_back.
- C++ "Pure Virtual Function Being Called"失败
- "Member function must be called or its address taken in function" C++错误
- 如何调试错误消息"abort() has been called"?
- Poco::Net::HTTPClientSession throw exception without unique_
- C++线程未加入"Termination called without active exception"
- 如何理解pthread_cancel导致"terminate called without an active exception"?
- std::thread - "terminate called without an active exception" ,不想"加入"它