when_any如何运作?

时间:2013-02-14 22:02:52

标签: windows-8 c++-cx ppl

我有一个std::vector< concurrency::task<void> >,其中包含可能会或可能不会按顺序加载的任务列表。我遇到了concurrency::when_any电话,但不知道如何使用它。

我遇到了使用该调用的this microsoft sample(ScenarioInput1.xaml.cpp:100),但我不理解pair参数,以及如何使其适应我的返回值。

编辑:我正在尝试做什么:

struct TaskInfo {
  unsigned int                    uniqueId;
  concurrency::task<unsigned int> task;
};
typedef std::vector< TaskInfo > TaskList;
typedef std::vector< unsigned int > TaskReturns;


// Somewhere inside a class, tasks and finished are member variable.
TaskList tasks;
bool finished = false;

// Inside a member function of the same class as above
// Populate the tasks

concurrency::when_any( tasks.begin(), tasks.end() ).then([this](std::vector<unsigned int> ids){
  for( std::vector<unsigned int>::iterator list=ids.begin; list != ids.end(); ++ids ) {
    // a mutex lock would happen here
    for( TaskList::iterator allTasks = tasks.begin(); allTasks != tasks.end(); ++allTasks ) {
      if ( *list == allTasks->uniqueId ) { tasks.erase( allTasks ); break; }
    }
    // mutex unlock
    if ( tasks.size() == 0 ) { finished = true; break }
  }
}

// In another member function
if ( finished ) doOtherThings();

如果我想要做的事情没那么高效,请告诉我。

2 个答案:

答案 0 :(得分:4)

这是任务的“选择”组合。你有一个延续(然后),一个连接(when_all)和选择(when_any)。 The docs say ......

  

创建在任何任务时成功完成的任务   作为参数提供成功完成。

有关详细信息,请参阅task classAsynchronous programming in C++More discussion and examples

以例如:

task<string> tasks[] = {t1, t2, t3};
auto taskResult =  when_all (begin(tasks), end(tasks))
    .then([](std::vector<string> results) {

......等同于......

(t1 && t2 && t3).then

然而......

task<string> tasks[] = {t1, t2, t3};
auto taskResult = when_any (begin(tasks), end(tasks))
    .then([](string result) {

......等同于......

(t1 || t2 || t3).then

答案 1 :(得分:1)

Hans Passant提供了this link,告诉我when_any( ... ).then([]( <params> )要求属于std::pair<returnType, size_t index>类型。