C++ Boost线程组线程限制器
我试图在任何时候限制线程的数量,使之等于可用内核的最大数量。以下方法是否合理?有更好的选择吗?谢谢C++ Boost线程组线程限制器,c++,boost,threadgroup,C++,Boost,Threadgroup,我试图在任何时候限制线程的数量,使之等于可用内核的最大数量。以下方法是否合理?有更好的选择吗?谢谢 boost::thread_group threads; iThreads = 0; for (int i = 0; i < Utility::nIterations; i++) { threads.create_thread( boost::bind(&ScenarioInventory::BuildIn
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();
}
boost::thread\u组线程;
iThreads=0;
对于(int i=0;inCores)
std::this_线程::sleep_for(std::chrono::毫秒(1));
}
线程。连接所有线程();
void ScenarioInventory::BuildInventoryWorker(inti)
{
//代码。。。。
螺纹限制器锁();
我读到--;
螺纹限制器。解锁();
}
您可能要寻找的是带有任务队列的线程池
有固定数量的线程阻塞队列。每当任务被推送到队列上时,工作线程就会收到信号(条件变量)并处理该任务
那样你
- 没有(低效的)等待锁
- 线程数不超过“最大值”
- 不必阻塞推送任务的代码
- 不要每次都重复创建线程