我試圖通過使用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