提升thread_group线程限制器
Boost thread_group thread limiter
我试图随时限制线程数,使其等于可用内核的最大数量。以下方法是否合理?有没有更好的选择? 谢谢!
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。
具有固定数量的线程阻止队列。每当任务被推送到队列中时,工作线程都会收到信号(条件变量)并处理任务。
这样你
- 没有(低效)等待锁
- 没有超过"最大值"的线程 数
- 不必阻止推送任务的代码
- 不要每次都冗余创建线程
有关带任务队列的此类线程池的两个不同演示,请参阅此答案: 并行计算大向量的总和
相关文章:
- 并行块(线程清理器)之外的 OpenMP 中的争用条件;误报?
- 线程清理器检测到数据争用,问题出在哪里?
- C++,如何创建线程限制/受保护的变量和函数
- 处理 std::线程包装器类的立即销毁
- 通过shared_ptr同步:线程清理器误报
- 将参数传递给 std::线程包装器
- 多线程包装器
- C++11 个线程限制
- 简单的线程计时器,请检查是否正常
- QML中的线程渲染器
- 线程包装器实现问题
- 控制台C++中的多线程定时器和I/O
- 在多线程环境中使用 std::string 时 Clang 的线程清理器警告
- 提升thread_group线程限制器
- 线程清理器的抑制文件不起作用:出了什么问题
- 多线程编写器:使用 cpp 的并发问题
- C++串行线程执行器
- 多线程定时器类
- 线程清理器报告使用嵌入式参考计数器时"data race on operator delete(void*)"
- 用类对象提升线程工作器