How to make boost::thread_group execute a fixed number of parallel threads(如何让 boost::thread_group 执行固定数量的并行线程)
问题描述
这是创建thread_group并并行执行所有线程的代码:
This is the code to create a thread_group and execute all threads in parallel:
boost::thread_group group;
for (int i = 0; i < 15; ++i)
group.create_thread(aFunctionToExecute);
group.join_all();
此代码将一次执行所有线程.我想要做的是并行执行它们,但最多 4 个.当 on 终止时,将执行另一个,直到没有更多要执行为止.
This code will execute all threads at once. What I want to do is to execute them all but 4 maximum in parallel. When on is terminated, another one is executed until there are no more to execute.
推荐答案
另一个更有效的解决方案是让每个线程在完成时回调到主线程,主线程上的处理程序可以启动一个新线程每一次.这可以防止对 timed_join 的重复调用,因为在触发回调之前主线程不会执行任何操作.
Another, more efficient solution would be to have each thread callback to the primary thread when they are finished, and the handler on the primary thread could launch a new thread each time. This prevents the repetitive calls to timed_join, as the primary thread won't do anything until the callback is triggered.
这篇关于如何让 boost::thread_group 执行固定数量的并行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何让 boost::thread_group 执行固定数量的并行线程
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01