提升thread_group线程限制器

时间:2016-02-11 16:39:18

标签: c++ boost threadgroup

我试图将任何时候的线程数限制为最大可用核心数。以下是合理的方法吗?还有更好的选择吗?谢谢!

    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();
}

1 个答案:

答案 0 :(得分:0)

您可能正在寻找的是带有任务队列的thread_pool。

有固定数量的线程阻塞队列。每当任务被推入队列时,工作线程就会发出信号(条件变量)并处理任务。

那样你

  • 没有(低效)等待锁
  • 除了&#34;最大&#34;
  • 之外不再有任何主题
  • 不必阻止推送任务的代码
  • 每次都没有多余的线程创建

有关具有任务队列的此类线程池的两个不同演示,请参阅此答案:Calculating the sum of a large vector in parallel