3

I'd like to use PPL "when_all" on tasks with different types. And add a "then" call to that task.

But when_all returns task that takes a vector, so all elements have to be the same type. So how do I do this?

This is what I have come up with but it feels like a bit of a hack:

//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;

Anyone got a better idea?

(parallel_invoke blocks so I dont want to use that)

4

1 回答 1

1

任务组将起作用。

做不到这一点:

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任务,而是将任何一组任务捆绑到一个元组任务中。

voids 工作需要更多的工作。一种方法是编写 aget_safe返回Tfortask<T>void_placeholderfor task<void>,然后在返回之前过滤结果元组。或者编写一个partition_args将 args 拆分为task<void>andtask<T>的方法,并对它们两个采取不同的操作。两人都有些头疼。我们还可以做一个元组附加模式(我们一次处理一个任务,并且可以将 a 附加T到 thetuple或什么都不做void)。

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

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

于 2015-06-20T22:21:31.640 回答