多线程包装器

Multithread wrapper

本文关键字:包装 多线程      更新时间:2023-10-16

在我的程序中,有很多循环可以轻松地重写为多线程。基本上,对于每个应该是多线程的函数,我正在编写以下功能:

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