回收父母作为孩子在tbb

时间:2013-03-19 19:04:06

标签: c++ multithreading tbb

我希望使用tbb::task并行化一个看似简单的问题。我的任务可以分成子任务,其数量不能选择,但由任务的状态决定(事先不知道)。由于父任务不需要其子任务的结果,我想将父项作为其子项进行回收。我在网上文档或示例中找不到一个好的工作示例,因此我的问题在这里。我目前的想法是按照这些方式进行编码:

struct my_task : tbb::task {
  typedef implementation_defined task_data;
  task_data DATA;
  my_task(task_data const&data) : DATA(data) {}
  void reset_state(task_data const&data) { DATA=data; }
  bool is_small() const;
  void serial_execution();
  bool has_more_sub_tasks() const;
  task_data parameters_for_next_sub_task();
  tbb::task*execute()
  {
    if(is_small()) {
      serial_execution();
      return nullptr;
    }
    tbb::empty_task&Continuation = allocate_continuation();     // <-- correct?
    task_data first_sub_task = parameters_for_next_sub_task();
    int sub_task_counter = 1;
    tbb::task_list further_sub_tasks;
    for(; has_more_sub_tasks(); ++sub_task_counter)
        further_sub_tasks.push_back(*new(Continuation.allocate_child())
                                     my_task(parameters_for_next_sub_task());
    Continuation.set_ref_count(sub_task_counter);               // <-- correct?
    spawn(further_sub_tasks);
    recycle_as_child_of(Continuation);                          // <-- correct?
    reset_state(first_sub_task);                                // change state
    return this;                                                // <-- correct?
  }
};

my_task*root_task = new(tbb::task::allocate_root())
                    my_task(parameters_for_root_task());
tbb::task::spawn_root_and_wait(*root_task);

这是正确的和/或最好的方法吗? (请注意,在上面的代码中,空的延续任务既不会产生也不会被返回)

1 个答案:

答案 0 :(得分:2)

创建延续的行应为:

  

tbb :: empty_task&amp; Continuation = * new(allocate_continuation())tbb :: empty_task;

set_ref_count和reset_state之间的逻辑看起来是正确的。

相关问题