多线程包装器
Multithread wrapper
在我的程序中,有很多循环可以轻松地重写为多线程。基本上,对于每个应该是多线程的函数,我正在编写以下功能:
void func_to_threaded(int i_from, int i_to, int num_th, ...other_parameters)
{
int i_min = i_from;
int i_max = i_to;
int i_inc = i_max / num_th;
i_max = i_max % num_th + i_inc;
thread* th_dens = new thread[num_th];
for (int i = 0; i < num_th; i++)
{
th_dens[i] = thread(func_one_thread, i_min, i_max, ...other_parameters);
i_min = i_max;
i_max += i_inc;
}
for (int i = 0; i < num_th; i++) th_dens[i].join();
delete[] th_dens;
}
是否可以将其重写为form
的每个功能的通用void func_one_thread(int i_min, int i_max, ...other_parameters)
我不会用模板回答您的问题,Altough肯定是一种有效的方法。我将要使用线程池,然后将您的所有操作包裹到一个通用的界面中。参见Eg。:1,2,带有增压:3
'保持高水平'
基于piotr falkowski的建议,我使用 boost
库的threadpool编写此类
// header file
#include "threadpool.hpp"
class c_Pool
{
public:
// CONSTRUCTORS
c_Pool(int num_thread);
// VARIABLES
int num_thread;
boost::threadpool::pool th_pool;
// METHODS
void add_task(int i_from, int i_to, std::function<void(int, int)> func);
};
// main file
c_Pool::c_Pool(int num_thread):
num_thread(num_thread), th_pool(num_thread)
{}
void c_Pool::add_task(int i_from, int i_to, function<void(int, int)> func)
{
int i_min = i_from;
int i_max = i_to;
int i_inc = (i_max - i_min) / num_thread;
i_max = i_from + i_inc // initial i_max
+ (i_max - i_min) % num_thread; // first thread is doing extra work
for (int i = 0; i < num_thread; i++)
{
auto func_one_thread = bind(func, i_min, i_max);
th_pool.schedule(func_one_thread);
i_min = i_max;
i_max += i_inc;
}
th_pool.wait();
}
和每个函数 void some_func(int i_min, int i_max, ...other_parameters)
i`m多线程,
auto tmp_func = bind(some_func, placeholders::_1, placeholders::_2, ...other_parameters);
pool.add_task(i_from, i_to, tmp_func);
编辑更正的行wth设置初始i_max
自从我问这个问题以来已经有一段时间了,我回到了一段时间后从boost threadpool移动到更优雅,更简单的OpenMP,如最初建议的Mark Setchell。所以我的代码现在看起来很简单
omp_set_num_threads(num_thread);
#pragma omp parallel for private(private_params)
for(int i = i_min; i < i_max; i++){
some_func(parameters);
}
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 多线程比没有线程C++慢
- 具有 C++11 多线程的特征库
- 为多线程环境包装 c++ new/delete 的安全/好方法
- 多线程包装器
- 从 C++ => C 包装的 API(多线程)传输错误字符串