Threaded Building Blocks (TBB) enqueue task with lambda

孤街醉人 提交于 2019-12-09 22:32:17

问题


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.

I am looking for a simple example of tbb::task::enqueue with a lambda expression.


回答1:


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

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

And then you might use this function with lambda expressions:

tbb_enqueue_lambda( []{ /* code here */ } );

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:

  • 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 inside lambda_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.


来源:https://stackoverflow.com/questions/22345935/threaded-building-blocks-tbb-enqueue-task-with-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!