我试图将任何时候的线程数限制为最大可用核心数。以下是合理的方法吗?还有更好的选择吗?谢谢!
boost::thread_group threads;
iThreads = 0;
for (int i = 0; i < Utility::nIterations; i++)
{
threads.create_thread(
boost::bind(&ScenarioInventory::BuildInventoryWorker, this,i));
thread_limiter.lock();
iThreads++;
thread_limiter.unlock();
while (iThreads > nCores)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
threads.join_all();
void ScenarioInventory::BuildInventoryWorker(int i)
{
//code code code....
thread_limiter.lock();
iThreads--;
thread_limiter.unlock();
}
答案 0 :(得分:0)
您可能正在寻找的是带有任务队列的thread_pool。
有固定数量的线程阻塞队列。每当任务被推入队列时,工作线程就会发出信号(条件变量)并处理任务。
那样你
有关具有任务队列的此类线程池的两个不同演示,请参阅此答案:Calculating the sum of a large vector in parallel