c++ - 多线程包装器

标签 c++ multithreading

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

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

有没有办法将其重写为对于表单的每个函数都是通用的

void func_one_thread(int i_min, int i_max, ...other_parameters)

最佳答案

我不会用模板来回答你的问题,尽管这肯定是一种有效的方法。我将建议使用线程池,并将所有操作包装到一个通用接口(interface)中。参见例如:1 , 2 ,增强:3

'stay high level '

关于c++ - 多线程包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936306/

相关文章:

c++ - 使用 namespace 和局部变量的状态 - 或类?

c++ - priority_queue 常量表达式

c++ - NUL 和 NULL 在 C 中可以互换吗?

c++ - 将 lambdas 传递给 std::thread 并调用类方法

ios - Realm 线程困惑

c++ - 为什么子类看不到我的重载函数

c++ - 类外的运算符重载

java - android:如何从用户定义的类访问 UI 对象

multithreading - 可重入锁和一般概念是什么?

c - 使用 swapcontext() 或 getcontext() & setcontext() 为线程库编写 yield() 函数