In the boost::thread library, is there any mechanism to control how many threads (at most) are running at a time?
In my case, it would be most convenient to start N threads all at the same time (N may be hundreds or a few thousand):
std::vector<boost::thread*> vec;
for (int i = 0; i < N; ++i) {
vec.push_back(new boost::thread(my_fct));
}
// all are running, now wait for them to finish:
for (int i = 0; i < N; ++i) {
vec[i]->join();
delete vec[i];
}
But I want Boost to transparently set a maximum of, say, 4 threads running at a time. (I’m sharing an 8-core machine, so I’m not supposed to run more than 4 at a time.)
Of course, I could take care of starting only 4 at a time myself, but the solution I’m asking about would be more transparent and most convenient.
Don’t think Boost.Thread has this built in but you can overlay Boost.Threadpool (not an official library) onto Boost.Thread, and that does allow you to control the thread count via
SizePolicy.The default is a fixed-size pool which is what you want – specify the initial (and ongoing) thread count on the
threadpoolconstructor.