c++ - 在 tbb 中回收 parent 作为 child

标签 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);

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

最佳答案

创建延续的行应该是:

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

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

关于c++ - 在 tbb 中回收 parent 作为 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508272/

相关文章:

algorithm - 线程构建 block 中嵌套循环的并行化

c++ - reduce_parallel 不是线程安全函数吗?

c++ - 为什么不能在常量表达式中使用 reinterpret_cast?

c++ - 派生类的 Push_back shared_ptr

c# - 在服务器上使用线程与异步编程

c# - ThreadPool 和带有 while(true) 循环的方法?

c++ - Intel TBB取得工作进展

c++ - 如何找到 2 张 map 中所有常见的键?

c++ - 错误:没有用于调用 QSortFilterProxyModel::setSourceModel(NavaidsModel&

c++ - OMP部分中的线程数