1

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

我遇到了这个使用调用 (ScenarioInput1.xaml.cpp:100) 的 microsoft 示例,但我不了解 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();

如果我想做的事情没有经过深思熟虑或效率不高,请告诉我。

4

2 回答 2

4

这是任务的“选择”组合。您有一个延续 (then)、一个连接 (when_all) 和选择 (when_any)。 文档说...

当作为参数提供的任何任务成功完成时,创建一个将成功完成的任务。

有关详细信息,请参阅C++中的任务类和异步编程。 更多讨论和示例

举个例子:

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
于 2013-02-14T23:25:51.327 回答
1

Hans Passant 提供了这个链接,告诉我when_any( ... ).then([]( <params> )需要是 type std::pair<returnType, size_t index>

于 2013-02-15T15:53:15.397 回答