PPL when_all不同类型的任务

PPL when_all with tasks of different types?

本文关键字:同类型 任务 all when PPL      更新时间:2023-10-16

我想在不同类型的任务上使用PPL "when_all"。并向该任务添加"then"调用。

但是when_all返回接受向量的任务,因此所有元素必须是相同的类型。那么我该怎么做呢?

这就是我想出的,但感觉有点黑客:

//3 different types:
int out1;
float out2;
char out3;
//Unfortunately I cant use tasks with return values as the types would be  different ...
auto t1 = concurrency::create_task([&out1](){out1 = 1; }); //some expensive operation
auto t2 = concurrency::create_task([&out2](){out2 = 2; }); //some expensive operation
auto t3 = concurrency::create_task([&out3](){out3 = 3; }); //some expensive operation
auto t4 = (t1 && t2 && t3); //when_all doesnt block
auto t5 = t4.then([&out1, &out2, &out3](){
    std::string ret = "out1: " + std::to_string(out1) + ", out2: " + std::to_string(out2) + ", out3: " + std::to_string(out3);
    return ret;
});
auto str = t5.get();
std::cout << str << std::endl;

有人有更好的主意吗?

(parallel_invoke块,所以我不想使用它)

任务组将起作用。

如果做不到这一点:

template<class...Ts>
struct get_many{
  std::tuple<task<Ts>...> tasks;
  template<class T0, size_t...Is>
  std::tuple<T0,Ts...>
  operator()(
    std::task<T0> t0,
    std::index_sequence<Is...>
  ){
    return std::make_tuple(
      t0.get(),
      std::get<Is>(tasks).get()...
    );
  }
  template<class T0>
  std::tuple<T0,Ts...>
  operator()(task<T0> t0){
    return (*this)(
      std::move(t0),
      std::index_sequence_for<Ts...>{}
    );
  }
};
template<class T0, class...Ts>
task<std::tuple<T0,Ts...>> when_every(
  task<T0> next, task<Ts>... later
){
  return next.then( get_many<Ts...>{
    std::make_tuple(std::move(later)...)
  } );
}

它不适用于void任务,但会以其他方式将任何一组任务捆绑到元组任务中。

void工作需要多做一些工作。 一种方法是编写一个get_safe,为task<T>返回T,为task<void>返回void_placeholder,然后在返回之前过滤生成的元组。 或者写一个partition_args,将参数分成task<void>task<T>,并对它们两个采取不同的行动。 两者都有点头疼。 我们还可以做一个元组追加模式(我们一次处理一个任务,并且可以将T附加到tuple,或者不做任何void)。

它使用两个C++14库功能(index_sequence和index_sequence_for),但两者都很容易用C++11编写(每个2-4行),并且实现很容易找到。

忘记了任务是否可以复制,我假设它不在上面的代码中。 如果它是可复制的,则上述代码的较短版本将起作用。 对于任何错别字,我们深表歉意。