线程构建块(TBB)使用lambda入队队列任务 [英] Threaded Building Blocks (TBB) enqueue task with lambda
问题描述
TBB文档提供了此示例使用lambda表达式与parallel_for,但不提供使用 tbb :: task :: enqueue
的lambda表达式的示例。
The TBB documentation gives this example of using lambda expressions with parallel_for, but doesn't provide an example of using lambda expressions with tbb::task::enqueue
.
我正在寻找一个带有lambda表达式的 tbb :: task :: enqueue
的简单示例。
I am looking for a simple example of tbb::task::enqueue
with a lambda expression.
推荐答案
TBB中的低级任务不直接支持lambda表达式。
Low-level tasks in TBB do not directly support lambda expressions. But with some extra coding you might create syntax-sugar helpers to do what you want.
你需要创建一个调用给定函子的任务类:
You'd need to create a task class that calls a given functor:
template<typename F>
class lambda_task : public tbb::task {
F my_func;
/*override*/ tbb::task* execute() {
my_func();
return NULL;
}
public:
lambda_task( const F& f ) : my_func(f) {}
};
然后,你需要创建一个函数模板,到 lambda_task
,并入列:
And then, you'd need to create a function template that takes a functor/lambda, wraps it into lambda_task
, and enqueues:
template<typename F>
void tbb_enqueue_lambda( const F& f ) {
tbb::task::enqueue( *new( tbb::task::allocate_root() ) lambda_task<F>(f) );
}
然后你可以使用这个函数和lambda表达式:
And then you might use this function with lambda expressions:
tbb_enqueue_lambda( []{ /* code here */ } );
支持lambda表达式的官方TBB API类,例如 task_group
和
task_arena
在内部使用非常相似的代码。
The official TBB API classes that support lambda expressions, such as task_group
and task_arena
, use very similar code internally.
更新:传递函数指针和参数以调用它,上述方法可以在某些方面扩展:
Update: to pass a function pointer and arguments to call it with, the above approach can be extended in some ways:
- C ++ 03,你需要为一个任务添加单独的类模板,一个参数,两个参数等,以及相应的
tbb_enqueue_lambda
函数 - 在C ++ 11中,可以使用可变参数模板,将实际参数存储在
lambda_task内的
,然后解包函数调用。开箱不是微不足道,但有一些SO主题覆盖已经:拆包调用匹配函数指针的元组,如何将元组扩展为可变参数模板函数的参数?和其他。std :: tuple
- In C++03, you'd need to add separate class templates for a task with one argument, two arguments, etc., and corresponding overloads of
tbb_enqueue_lambda
function - In C++11, you could use variadic templates, storing the actual arguments in an
std::tuple
insidelambda_task
, and 'unpacking' those for the function call. Unpacking is not trivial, but there are a few SO topics covering that already: "unpacking" a tuple to call a matching function pointer, How do I expand a tuple into variadic template function's arguments?, and other.
这篇关于线程构建块(TBB)使用lambda入队队列任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!