提升thread_group线程限制器

Boost thread_group thread limiter

本文关键字:线程 限制器 group thread 提升      更新时间:2023-10-16

我试图随时限制线程数,使其等于可用内核的最大数量。以下方法是否合理?有没有更好的选择? 谢谢!

    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。

具有固定数量的线程阻止队列。每当任务被推送到队列中时,工作线程都会收到信号(条件变量)并处理任务。

这样你

  • 没有(低效)等待锁
  • 没有超过"最大值"的线程
  • 不必阻止推送任务的代码
  • 不要每次都冗余创建线程

有关带任务队列的此类线程池的两个不同演示,请参阅此答案: 并行计算大向量的总和