ThreadPool 传递函数作为参数

ThreadPool pass function as argument

我正在尝试实现我自己的并行版本以使用 https://github.com/Fdhvdu/ThreadPool 作为后端线程池

我将任务分成几个部分并启动一个具有以下功能的线程:

template <typename Callable>
void launchRange(int id, Callable func, int k1, int k2)
{
    for (int k = k1; k < k2; k++) {
        func(k);
    }
}

我遇到的问题是如何将这个Callable传递给线程池

相关部分是:

poolPtr->add(launchRange, func, i1, i2);

但我不断收到编译错误。错误是:

...\ithreadpoolitembase.hpp(36): error C2027: use of undefined type 'std::tuple<conditional<_Test,void(__cdecl *&)(int),_Ty>::type,conditional<_Test,int&,int>::type,conditional<_Test,int&,int>::type>'
with
[
    _Ty=void (__cdecl *)(int)
]

add的界面是

template<class Func,class ... Args>
inline thread_id add(Func &&func,Args &&...args);

我正在使用 Visual Studio 2017 Community 15.4 和 /std:c++17

launchRange 是函数模板而不是函数。

除非重载解析已完成,否则不能将函数模板作为函数传递。该行不会触发重载决议。

auto launchRange = [](int id, auto&& func, int k1, int k2)
{
  for (int k = k1; k < k2; k++) {
    func(k);
  }
};

上面是一个 lambda,它的行为很像 launchRange 模板,但它是一个实际对象,而不仅仅是一个模板。

它仍然无法工作,因为你没有传递 add id 参数。

poolPtr->add(launchRange, 77, func, i1, i2);

这可能会编译。

我不是特别喜欢那个特定的线程池实现。我的意思是,您可以拥有多少毫无意义的 pimpl 层?多少无意义的堆分配?而且,它 默认通过引用传递 ,这在将内容传递给另一个线程时是一个可怕的想法。

我认为在这里接受争论是一个糟糕的计划。避免使用它们。

poolPtr->add([=]{ launchRange(77, func, i1, i2); });

这也消除了创建 auto launchRange = [] lambda 的需要。错误最终更容易阅读。