Boost thread_group线程限制器
问题描述:
我试图在任何时候限制线程的数量,使其等于最大可用内核的数量。以下是一个合理的方法吗?有更好的选择吗?谢谢!Boost thread_group线程限制器
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();
}
答
你很可能在寻找的是带有任务队列的thread_pool。
有固定数量的线程阻塞队列。每当一个任务被推入队列时,一个工作线程就会发出信号(条件变量)并处理任务。
这样,你
- 没有(低效率)等待锁
- 没有任何更多的线程,比“最大”
- 没有在代码中阻止他们推送任务
- 没有多余的线程的创建围绕
每次看到这个答案对于这样一个THRE两个不同的演示有任务队列的广告池:Calculating the sum of a large vector in parallel