【问题标题】:Boost thread_group thread limiterBoost thread_group 线程限制器
【发布时间】:2016-02-11 16:39:17
【问题描述】:

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

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

【问题讨论】:

    标签: c++ boost threadgroup


    【解决方案1】:

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

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

    这样你

    • 不要有(低效的)等待锁
    • 线程数不能超过“最大值”
    • 不必阻塞在推送任务的代码中
    • 不要每次都重复创建线程

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

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 2016-06-06
      • 2015-04-04
      • 2020-03-19
      • 2013-05-16
      • 2011-11-05
      • 1970-01-01
      • 2012-04-11
      • 2020-06-17
      相关资源
      最近更新 更多