I'm trying to speed up a for loop by using std::thread
. The loop iterates over a list consisting of several million items. I give each iteration to a different thread.
After 4047 iterations it stops running and throws terminate called without an active exception Aborted (core dumped)
I believe this error usually caused by the threads not being properly joined (as stated in other questions on this site). However I do have a function to join all threads at the end of my for loop. Because the join function is not being reached I suspect the real problem is there are too many threads created. This is my first foray into lambdas and multithreading and I'm not sure how to limit the number of threads created at a time within a for loop.
My code is as follows:
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
});
Any help would be much appreciated