【发布时间】:2016-03-15 03:30:15
【问题描述】:
我维护了一个开源无锁线程库,专为高速并行循环展开而设计,用于几个商业视频游戏。它的开销非常低,大约 8 个时钟用于创建消息,大约 500 个时钟(每个线程,包括延迟)用于整个调度和远程执行开销。我先这么说是为了解释为什么我不简单地使用 use std::function 和 bind。
该库将函数调用和函数调用的参数打包在一条消息中(Functor 类型)。然后使用参数副本远程调用它。
我最近重写了该库,以使用 STL 样式模板元编程而不是它最初使用的过时的 C 样式宏来打包远程调用。令人惊讶的是,这只增加了两个滴答声的开销,但我不知道如何创建一个同时接受 lambda 和函数指针的打包函数。
所需用途:
CreateFunctor([](int a, int b){doSomething(a, b)}, 1, 2);
或
CreateFunctor(&doSomething, 1, 2);
目前我必须将这些情况分为两个单独的函数(CreateFunctor 和 CreateFunctorLambda)。如果我可以将它们结合起来,我将能够将我的打包和调度阶段合并为一个简洁的函数调用并简化 API。
问题在于推导 lambda 参数的代码似乎无法与推导函数参数的代码共享模板覆盖。我试过使用 enable_if ,它仍然执行 lambda 版本的 ::* 部分,并导致编译器错误与函数指针。
相关片段:
template <typename... Arguments>
inline Functor<Arguments...> CreateFunctor(void(*func)(Arguments...))
{
return Functor<Arguments...>(func);
};
template <typename... Arguments>
inline Functor<Arguments...> CreateFunctor(void(*func)(Arguments...), Arguments ... arg)
{
Functor<Arguments...> ret(func);
ret.Set(arg...);
return ret;
};
// template to grab function type that lambda can be cast to
// from http://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda
template <class T>
struct deduce_lambda_arguments
: public deduce_lambda_arguments<typename std::enable_if<std::is_class<T>::value, decltype(&T::operator())>::type>
{};
template <class ClassType, typename... Args>
struct deduce_lambda_arguments<void(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
typedef void(*pointer_cast_type)(Args...);
typedef Functor<Args...> functor_type;
};
template <typename F, typename... Args>
inline auto CreateFunctorLambda(F f, Args... arg) -> typename deduce_lambda_arguments<F>::functor_type
{
deduce_lambda_arguments<F>::functor_type ret((deduce_lambda_arguments<F>::pointer_cast_type) f);
ret.Set(arg...);
return ret;
};
template <typename F>
inline auto CreateFunctorLambda(F f) -> typename deduce_lambda_arguments<F>::functor_type
{
return deduce_lambda_arguments<F>::functor_type((deduce_lambda_arguments<F>::pointer_cast_type) f);
};
【问题讨论】:
-
如果我没看错,你只接受无捕获的非泛型 lambda,对吗?
-
正确。它们都被转换为一个结构,其中包含一个 __cdecl 函数指针、一个参数列表和一个大小。捕获会使这变得更加复杂,并且无论如何对于延迟执行都是不安全的。一旦知道参数,就可以将 lambda 转换为 __cdecl 指针并与一个 mov 一起存储。
-
你测量过 std::function 的性能吗?它对函数对象“小”时进行了优化。如果你能超越它,我会感到惊讶。
-
Richard,是的,我已经评估了 std::function 的速度(在这种情况下需要绑定,非常不轻量级)。即使对于带有 void 参数的非常小的或空的外壳,使用 std::function 也会将开销时间从每个线程作业开始的大约 150 微秒增加到大约 400 微秒。这包括排队和线程间通信。对于大多数应用程序来说都很好,但对于更大的功能,由于内存管理,它变得昂贵了 2 个数量级。
-
你能分享你图书馆的链接吗?
标签: c++ templates c++11 lambda variadic-templates